🚀 Day 4 of 50 Days Coding Challenge Today I solved a problem on Hashing Pattern 🔹 Problem: Two Sum 🔹 Approach: First tried brute force using nested loops (checking all pairs) Then optimized using HashMap (Hashing concept) to reduce time complexity 🔹 Key Learning: Instead of checking every pair, we can store values and directly check if the required complement exists. This reduces time complexity from O(n²) → O(n) 🚀 Also learned an important concept: 👉 need = target - current element 🔹 Time Complexity: O(n) 🔹 Code (Java): import java.util.*; class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int need = target - nums[i]; if(map.containsKey(need)) { return new int[]{map.get(need), i}; } map.put(nums[i], i); } return new int[]{-1, -1}; } } 💡 Consistency > Motivation #coding #leetcode #100DaysOfCode #java #programming #dsa #learning #hashmap
Solving Two Sum Problem with Hashing in Java
More Relevant Posts
-
🚀 Mastering Java Through LeetCode 🧠 Day 33 Not all nodes are “Good”… but finding them made me better at Trees 📌 LeetCode Problem Solved: Q.1448 – Count Good Nodes in Binary Tree 💭 Problem Summary: A node is called “Good” if no node on the path from root to it has a greater value. 🎯 Approach: ✔ Used DFS (Depth First Search) ✔ Tracked the maximum value seen so far in the path ✔ If current node ≥ maxSoFar → count it as a Good Node ✔ Updated max and continued recursion 🧠 Key Insight: Instead of storing the full path, just carry maxSoFar — simple yet powerful optimization! 💡 Complexity: ⏱ Time: O(N) 📦 Space: O(H) 🔥 What I Learned: How to maintain state during recursion Clean way to solve tree problems using DFS Thinking in terms of path-based conditions Consistency builds confidence 💪 Day 33 done… Let’s keep going 🚀 #Java #LeetCode #DataStructures #Algorithms #CodingJourney #100DaysOfCode #DSA #Tech #Learning
To view or add a comment, sign in
-
-
Deep Dive: Java Priority Queue & Binary Min Heaps 🚀 Today’s session at TAP Academy with Sharath R sir was a masterclass in internal data structures. We moved beyond simple usage to understand how Java’s PriorityQueue actually manages data under the hood. Technical Key Takeaways: Internal Architecture: Unlike standard queues, the PriorityQueue uses a Binary Min Heap. This ensures the smallest element always occupies the root position, maintaining a "parent < children" relationship throughout the tree. The Power of O(log n): Whether you are inserting an element or polling one, the structure maintains its integrity through Heapify Up and Heapify Down processes, ensuring high efficiency even with large datasets. The poll() vs. iterator() Trap: This was a crucial highlight! Using a for-each loop or iterator only traverses the internal array level-by-level, which does not guarantee sorted order. To actually retrieve elements in their prioritized (sorted) sequence, you must use the poll() method. Strict Properties: Initial Capacity: 11. Null Safety: No null values allowed. Data Integrity: Only homogeneous (comparable) data is permitted to avoid ClassCastException. Understanding these "under the hood" mechanics is what separates a coder from an engineer. Huge thanks to Sharath R sir for breaking down these complex heap operations so effectively! #Java #CollectionsFramework #PriorityQueue #DataStructures #TAPAcademy #Programming #TechLearning #BinaryHeap #ComputerScience #SoftwareEngineering #SharathSir
To view or add a comment, sign in
-
-
Day 73 of #90DaysDSAChallenge Solved LeetCode 451: Sort Characters By Frequency Learned an important Java design concept today. Problem Overview: The task was to sort characters in a string based on descending frequency. What confused me initially: Why create a separate Freq class instead of just using HashMap and PriorityQueue directly? Key Learning: PriorityQueue stores one complete object at a time. For this problem, each item needs two pieces of data together: Character Frequency Example: Instead of storing: e and 2 separately We package them as: Freq('e', 2) That custom class acts like a container holding both values in one object, so PriorityQueue can compare and sort them correctly. Why this matters: This taught me that custom classes in Java are often not about complexity, they simply bundle related data into one manageable unit. Alternative approach: We can also use Map.Entry<Character, Integer> instead of creating a custom class, but building Freq makes the logic easier to understand while learning. Today’s takeaway: Not every class is for business logic — sometimes it exists just to package data cleanly. #Java #90DaysDSAChallenge #LeetCode #PriorityQueue #HashMap #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Mastering Java Through LeetCode 🧠 Day 20 of My DSA Journey Today I solved another problem from the LeetCode 75 list to improve my understanding of HashMap and HashSet concepts and strengthen my problem-solving skills. 📌 LeetCode Problem Solved Today: Q.1207 – Unique Number of Occurrences 💡 Problem Statement: Given an integer array arr, return true if the number of occurrences of each value in the array is unique, otherwise return false. 🧩 Example 1: Input: [1,2,2,1,1,3] Output: true 🧩 Example 2: Input: [1,2] Output: false Key Learning: Today I learned how to efficiently solve problems using Hashing techniques: ✔️ Use HashMap to count frequency of each number ✔️ Use HashSet to check if frequencies are unique ✔️ If any frequency repeats → return false 🧠 Approach: 1️⃣ Traverse array and store frequency using getOrDefault() 2️⃣ Traverse map values 3️⃣ Check duplicates using HashSet ⏱️ Complexity: Time Complexity: O(n) Space Complexity: O(n) This problem helped me understand how frequency counting + uniqueness checking works in real interview scenarios. Consistency is the key — solving problems daily to become a better software engineer 💻 #LeetCode #Java #DSA #ProblemSolving #CodingJourney #LearningInPublic #SoftwareDevelopment #Programming #Coding #Tech #Developers #100DaysOfCode #TechCareer #InterviewPreparation #HashMap #HashSet #CodingPractice #PGCP #CDAC #LeetCode75
To view or add a comment, sign in
-
-
Day 62 of Sharing What I’ve Learned🚀 Iterator in Java — Safe and Efficient Traversal After understanding how collections store and organize data, I revisited an important concept — how to safely traverse them using Iterator. 👉 Accessing data is easy… but doing it correctly and safely matters more. 🔹 What is an Iterator? Iterator is an interface in Java used to traverse elements of a collection one by one. 👉 It provides a standard way to loop through: ArrayList HashSet LinkedList And more… 🔹 Why not just use a for loop? Using a normal loop works… but it has limitations: ❌ Not safe when modifying collection ❌ Can lead to ConcurrentModificationException ❌ Not universal for all collection types 👉 That’s where Iterator comes in ✔ 🔹 Key Methods of Iterator hasNext() → checks if next element exists next() → returns the next element remove() → removes the current element safely 🔹 Example import java.util.*; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); Iterator<String> it = list.iterator(); while(it.hasNext()) { String lang = it.next(); System.out.println(lang); } } } 🔹 Real Advantage 💡 👉 Removing elements while iterating: Iterator<String> it = list.iterator(); while(it.hasNext()) { if(it.next().equals("Python")) { it.remove(); // Safe removal } } ✔ No errors ✔ Clean logic ✔ Interview-friendly concept 🔹 Day 62 Realization Traversing data is not just about loops — it’s about doing it safely and efficiently. 👉 Iterator provides better control and prevents runtime issues 👉 Essential when working with dynamic collections #Java #Collections #DataStructures #CollectionsFramework #Iterator #Programming #DeveloperJourney #100DaysOfCode #Day61 Grateful for guidance from, TAP Academy Sharath R kshitij kenganavar
To view or add a comment, sign in
-
-
Day 31 of #50DaysLeetCode Challenge 💻🔥 Today I solved the “Permutations” problem using Java. 🔹 Problem: Given an array of distinct integers, return all possible permutations. 🔹 Reality check: If you don’t understand recursion properly, this problem will expose you. There’s no shortcut here. 🔹 Approach (Backtracking): Fix one element at a time Swap it with every possible choice Recurse for the remaining positions Backtrack (undo the swap) to explore other possibilities 🔹 Key Insight: This isn’t about generating values — it’s about exploring a decision tree. Every level = a position in the array Every branch = a choice 🔹 Time Complexity: O(n!) — and that’s unavoidable 📌 What I learned: Backtracking is not optional for DSA. If you try to avoid it, you’ll get stuck on a whole category of problems. Stop memorizing patterns blindly. Understand why the recursion works. #Day25 #LeetCode #Java #Backtracking #DSA #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 3 of My Coding Challenge Improving my problem-solving skills step by step! Today I solved a number-based problem on reversing an integer. 🔹 Platforms: LeetCode & GeeksforGeeks 🔹 Problem: LeetCode #7 – Reverse Integer 🔹 Problem Statement: Given a signed 32-bit integer, reverse its digits. If the reversed integer overflows, return 0. 🔹 Approach: 1️⃣ Extract last digit using modulo (%) 2️⃣ Build reversed number step by step 3️⃣ Check for overflow before updating result 🔹 Example: Input: 123 → Output: 321 Input: -123 → Output: -321 Input: 120 → Output: 21 🔹 What I learned: ✔ Handling integer overflow conditions ✔ Working with digits using modulo & division ✔ Writing safe and optimized code 💻 Code: import java.util.*; public class ReverseIntegerLeetCode7 { ``` public static int reverse(int x) { int rev = 0; while (x != 0) { int rem = x % 10; x = x / 10; // Check overflow if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && rem > 7)) { return 0; } if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && rem < -8)) { return 0; } rev = (rev * 10) + rem; } return rev; } public static void main(String[] args) { int x = 123; System.out.println(reverse(x)); x = -123; System.out.println(reverse(x)); x = 120; System.out.println(reverse(x)); } ``` } 🔗 GitHub: https://lnkd.in/g-wNSrPq #Java #DSA #LeetCode #CodingChallenge #50DaysChallenge #Consistency #GrowthMindset #LearningJourney
To view or add a comment, sign in
-
Stop choosing between Java and Python. In 2026, the market demands "Dual-Stack" proficiency. The roadmap to becoming a high-performance architect has changed. With Java 26 arriving and AI integration becoming the standard, mastering both Java and Python is no longer optional - it's a competitive advantage. At MyExamCloud, we use our proven PPA (Plan, Practice, Achieve) methodology to ensure you don't just study-you certify. Link in comments. #Java26 #PythonCertification #SoftwareArchitecture #MyExamCloud #CareerGrowth
To view or add a comment, sign in
-
Day 56 of Sharing What I’ve Learned🚀 TreeSet in Java — Sorted & Unique Elements After exploring how LinkedHashSet maintains insertion order, I moved to something even more powerful — TreeSet. 👉 It not only stores unique elements but also keeps them automatically sorted 🔹 What is TreeSet? TreeSet is an implementation of the Set interface that stores unique elements in sorted order. 👉 It is internally based on a Red-Black Tree (self-balancing binary search tree) 🔹 How does TreeSet store & sort data? 👉 Elements are stored in a tree structure, not randomly 👉 While inserting, elements are placed in a way that keeps the tree balanced 👉 Data is always arranged in ascending order (default) ✔ Smallest element → left side ✔ Largest element → right side ✔ In-order traversal → gives sorted output 🔹 Why use TreeSet? ✔ Sorted Data Elements are always in ascending order ✔ No Duplicates Just like other Sets, duplicates are not allowed ✔ Navigable Operations Supports methods like higher(), lower(), ceiling(), floor() 🔹 Key Features ✔ Stores unique elements ✔ Automatically sorts elements ✔ Does NOT allow null values ✔ Slower than HashSet & LinkedHashSet (due to sorting) 🔹 Important Methods ✔ add() ✔ remove() ✔ contains() ✔ first() / last() ✔ higher() / lower() 🔹 When should we use TreeSet? 👉 Use TreeSet when: ✔ You need sorted data ✔ You want range-based operations ✔ You need navigation (greater/smaller elements) 🔹 When NOT to use? ❌ When order doesn’t matter → use HashSet ❌ When insertion order matters → use LinkedHashSet ❌ When performance is critical (faster ops needed) 🔹 Key Insight 💡 TreeSet is like a self-sorting set — 👉 You don’t sort the data, it sorts itself automatically 🔹 Day 56 Realization 🎯 Data structures are not just about storing data… 👉 they define how efficiently you can retrieve, organize, and use it #Java #TreeSet #DataStructures #CollectionsFramework #Programming #DeveloperJourney #100DaysOfCode #Day56 Grateful for guidance from, Sharath R TAP Academy
To view or add a comment, sign in
-
-
🚀 Mastering Java Through LeetCode 🧠 Day 32 Today I solved an Easy-level Tree problem that strengthened my understanding of Recursion + Depth Calculation — a fundamental concept for tree-based problems 📌 LeetCode Problem Solved: Q.104. Maximum Depth of Binary Tree 💭 Problem Summary: Given a binary tree, the task is to find the maximum depth — i.e., the number of nodes along the longest path from root to leaf. 🧠 Approach (Optimal): Instead of iterating level by level, I used a clean recursive approach: ✔️ If node is null → return 0 ✔️ Recursively calculate left subtree depth ✔️ Recursively calculate right subtree depth ✔️ Return 1 + max(left, right) ⚡ Key Learning: Recursion makes tree problems much simpler when you think in terms of “what should each function return for a node?” Complexity: Time: O(n) Space: O(h) Takeaway: Tree problems become easier once you master recursion and start recognizing patterns. Consistency is the key — showing up every day #Day32 #LeetCode #Java #DSA #CodingJourney #Recursion #BinaryTree #100DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development