HashMap Internal Working — How put() Actually Works 🔍 When you write: Map<String, String> map = new HashMap<>(); map.put("name", "Java"); Let’s see what happens internally 👇 Step 1 → hashCode() ▸ HashMap calculates hash of the key ▸ Example: "name".hashCode() → 3373707 Step 2 → Index Calculation ▸ index = hash & (n - 1) ▸ Determines the bucket where data will be stored Step 3 → Store Entry in Bucket ▸ If bucket is empty → stores Entry(key, value) directly ▸ If bucket already has elements → collision handling happens → equals() checks keys → Same key → value replaced → Different key → added to LinkedList Step 4 → Java 8 Optimization ⚡ ▸ If bucket size becomes > 8 nodes ▸ LinkedList converts into Red-Black Tree ▸ Search complexity improves: O(n) → O(log n) Example: map.put("name", "Java"); map.put("name", "Python"); // replaces old value map.get("name"); // returns "Python" #Java #JVM #HashMap #Collections #JavaDeveloper #SpringBoot
Monu Alam’s Post
More Relevant Posts
-
Day 95 of #365DaysOfLeetCode Challenge Today’s problem: **Path Sum III (LeetCode 437)** This one looks like a typical tree problem… but the optimal solution introduces a powerful concept: **Prefix Sum + HashMap in Trees** 💡 **Core Idea:** Instead of checking every possible path (which would be slow), we track **running sums** as we traverse the tree. 👉 If at any point: `currentSum - targetSum` exists in our map → we’ve found a valid path! 📌 **Approach:** * Use DFS to traverse the tree * Maintain a running `currSum` * Store prefix sums in a HashMap * Check how many times `(currSum - targetSum)` has appeared * Backtrack to maintain correct state ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Prefix Sum isn’t just for arrays — it can be **beautifully extended to trees**. This problem completely changed how I look at tree path problems: 👉 From brute-force traversal → to optimized prefix tracking 💭 **Key takeaway:** When a problem involves “subarray/paths with a given sum,” think: ➡️ Prefix Sum + HashMap #LeetCode #DSA #BinaryTree #PrefixSum #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
**Day 113 of #365DaysOfLeetCode Challenge** Today’s problem: **Contiguous Array (LeetCode 525)** We need to find the **longest contiguous subarray** with an equal number of `0`s and `1`s. At first glance, it feels like a sliding window problem… but the real solution is: 👉 **Prefix Sum + HashMap** 💡 **Core Idea:** Convert: * `0 → -1` * `1 → +1` Now the problem becomes: 👉 Find the longest subarray whose sum = `0` Because equal number of `0`s and `1`s cancel each other out. 📌 **Approach:** 1️⃣ Maintain running sum 2️⃣ Store first occurrence of each sum in HashMap 3️⃣ If same sum appears again: * Subarray between those indices has sum `0` 4️⃣ Maximize length 💡 Why store first occurrence only? Because earliest index gives the **longest possible subarray** ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Many binary array problems can be transformed into prefix sum problems by clever value mapping. 💭 **Key Takeaway:** When asked: * Equal 0s and 1s * Balanced values * Longest valid subarray Think: 👉 Prefix Sum 👉 HashMap 👉 First occurrence trick #LeetCode #DSA #PrefixSum #HashMap #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Some problems are not just about algorithms — they test your ability to design efficient data structures. 🚀 Day 118/365 — DSA Challenge Solved: LRU Cache Problem idea: Design a cache that supports get and put in O(1), while removing the least recently used (LRU) item when capacity is exceeded. Efficient approach: Combine HashMap + Doubly Linked List. Steps: 1. Use HashMap to store key → node (O(1) access) 2. Use Doubly Linked List to maintain usage order 3. Most recently used → near head 4. Least recently used → near tail 5. On get/put: - Move node to front (mark as recently used) 6. If capacity exceeds: - Remove node from tail (LRU) This ensures all operations run in constant time. ⏱ Time: O(1) per operation 📦 Space: O(capacity) Day 118/365 complete. 💻 247 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #LinkedList #HashMap #SystemDesign #LeetCode #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 5 – What Really Happens Inside a HashMap? We use "HashMap" almost everywhere, but its internal working is quite interesting. Map<String, Integer> map = new HashMap<>(); map.put("key", 1); What happens internally? 👉 Step 1: "hashCode()" is calculated for the key 👉 Step 2: Hash is converted into an index (bucket location) 👉 Step 3: Value is stored in that bucket 💡 But what if two keys land in the same bucket? ✔ This is called a collision ✔ Java handles it using a Linked List (and converts to a Tree if it grows large) ⚠️ Important: - Retrieval ("get") again uses "hashCode()" + ".equals()" - So both must be properly implemented for custom objects 💡 Real takeaway: Good hashing = better performance Poor hashing = more collisions = slower operations This is why "HashMap" is fast on average (O(1)), but can degrade if not used properly. #Java #BackendDevelopment #HashMap #JavaInternals #LearningInPublic
To view or add a comment, sign in
-
Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
To view or add a comment, sign in
-
-
🚀 Day 87 — Prefix Sum Pattern (Subarray Sum Equals K) Continuing the prefix sum deep dive — today I solved the classic problem of counting subarrays that sum to a given value k. This is where the HashMap optimization truly shines. 📌 Problem Solved: LeetCode 560 – Subarray Sum Equals K 🧠 Key Insight – Prefix Sum + HashMap: java Map<Integer,Integer> map = new HashMap<>(); map.put(0, 1); // empty prefix sum int sum = 0, res = 0; for (int num : nums) { sum += num; int diff = sum - k; res += map.getOrDefault(diff, 0); map.put(sum, map.getOrDefault(sum, 0) + 1); } return res; Why this works: sum at index i = prefix sum from 0 to i. If sum - k exists as a prefix sum before, then the subarray between that previous index and i sums to k. HashMap stores frequency of each prefix sum, allowing O(1) lookups. Why not brute force? Brute force: O(n²) — check every subarray. Prefix sum + HashMap: O(n) time, O(n) space. Edge cases to handle: k = 0 → subarrays summing to zero. Negative numbers → prefix sums can decrease, but HashMap still works. Initial map.put(0,1) ensures subarrays starting at index 0 are counted. 💡 Takeaway: When the problem asks for “number of subarrays with sum = k”, think prefix sum + HashMap immediately. This is the second category from the prefix sum flowchart — exact sums require hash‑based lookup. No guilt about past breaks — just building pattern recognition, one problem at a time. #DSA #PrefixSum #SubarraySumEqualsK #LeetCode560 #HashMap #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 11 — Streams, Partitioned Logs, and Consumer Groups Queues are useful when work needs to be processed asynchronously. But Day 11 helped me understand a different pattern: 👉 when events need to be stored, replayed, and consumed by multiple independent systems. That is where streams and partitioned logs become important. Because in event-driven systems, data is not just passed from one service to another. It becomes a continuous flow that different consumers may process in different ways. Today’s focus was: Streams, Partitioned Logs, and Consumer Groups 📊 What I covered today 📘 📜 Append-only event logs 🧩 Partitioning for scale 🔑 Ordering guarantees and key-based routing 👥 Consumer groups and offset tracking 🔁 Replay and recovery 📉 Lag monitoring and backpressure What stood out to me ✅ Append-only logs make replay, auditing, and recovery much easier ✅ Partitioning improves throughput, but ordering is only guaranteed within a partition ✅ Key-based routing helps keep related events together ✅ Consumer groups allow multiple applications to process the same stream independently ✅ Offset tracking is critical because consumers should resume from where they stopped ✅ Consumer lag is one of the most important signals in stream processing systems I also implemented a small Partitioned Log with Consumer Offsets sample in Python and Java to make the concept more practical. 🛠️ ➡️ Git: https://lnkd.in/dPKzP2B5 That helped me understand a simple but important idea: 📌 Streams are not just queues 📌 Replay is a feature, not a bug 📌 Offset tracking is what makes recovery possible This is one of those topics that becomes much clearer when you build even a small version of it. Producing events is simple, but handling partitions, offsets, replay, and lag is where the real system design thinking starts. System Design is slowly becoming less about moving data from one place to another and more about building data flows that are scalable, replayable, and reliable under load. On to Day 12 📈 #SystemDesign #DistributedSystems #BackendEngineering #SoftwareEngineering #ScalableSystems #Streams #EventStreaming #PartitionedLogs #ConsumerGroups #OffsetTracking #Kafka #ApacheKafka #EventDrivenArchitecture #MessageQueues #AsyncProcessing #DataStreaming #StreamProcessing #Backpressure #ConsumerLag #Microservices #SystemArchitecture #BackendDevelopment #CloudComputing #Java #Python
To view or add a comment, sign in
-
🚀 Day 85 of #100DaysOfCode Solved 106. Construct Binary Tree from Inorder and Postorder Traversal on LeetCode 🔗 🧠 Key Insight: 👉 Postorder = Left → Right → Root 👉 Last element in postorder = root of tree 👉 Inorder = Left → Root → Right 👉 Use inorder to split into left & right subtrees ⚙️ Approach (HashMap + Recursion): 1️⃣ Take last element of postorder 🔹 This is the root 2️⃣ Find root index in inorder 🔹 Split inorder into: • Left subtree • Right subtree 3️⃣ Build subtrees recursively: 🔹 Important order: 👉 Build right subtree first, then left (because we are consuming postorder from end) 4️⃣ Use a HashMap: 🔹 Store inorder value → index 👉 For O(1) lookup ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #BinaryTree #Recursion #DivideAndConquer #HashMap #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 88 — Prefix Sum Pattern (Pivot Index) Continuing the prefix sum journey — today I solved a problem that finds the equilibrium point where the sum of elements to the left equals the sum to the right. This is a great example of optimizing space using simple math. 📌 Problem Solved: LeetCode 724 – Find Pivot Index 🧠 Optimized Approach – Single Pass with Total Sum: java int total = 0, leftSum = 0; for (int num : nums) total += num; for (int i = 0; i < nums.length; i++) { // rightSum = total - leftSum - nums[i] if (leftSum == total - leftSum - nums[i]) return i; leftSum += nums[i]; } return -1; Why this works: total = sum of all elements. At index i, rightSum = total - leftSum - nums[i]. No need to store prefix/suffix arrays — just update leftSum as we go. Space complexity drops from O(n) to O(1). Key Insight from Revision: Earlier we discussed the Pivot Index optimization using the relationship: Total Sum = Left Sum + arr[i] + Right Sum → Right Sum = Total Sum - Left Sum - arr[i] This eliminates extra arrays. Edge Cases: Pivot at index 0 → left sum = 0. Pivot at last index → right sum = 0. No pivot → return -1. 💡 Takeaway: Not every prefix sum problem needs extra arrays. Recognizing when you can derive one side from the total sum and the other side saves space and simplifies code. No guilt about past breaks — just mastering optimizations within patterns. #DSA #PrefixSum #PivotIndex #LeetCode724 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
𝐃𝐚𝐲 𝟕𝟑 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on detecting duplicates within a given index range. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Contains Duplicate II --- 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 • Stored each number with its latest index • For every element: • Checked if it already exists in the map • If yes → verified index difference ≤ k • Updated index to keep the most recent occurrence --- 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Storing indices helps solve range-based problems • HashMap enables O(1) lookup • Updating latest index ensures correctness • Small constraints can change the approach --- 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(n) --- 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Adding constraints doesn’t always make problems harder — it often makes them more interesting to solve. --- 73 days consistent 🚀 On to Day 74. #DSA #Arrays #HashMap #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
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