🚀 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
HashMap Internal Working and Collision Handling in Java
More Relevant Posts
-
𝐃𝐚𝐲 𝟕𝟑 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 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
-
-
🚀 Day 04/60 of My Consistency Challenge – Mastering Java Map Implementations Today I explored three core Map implementations in the Java Collection Framework: 🔹 HashMap 🔹 LinkedHashMap 🔹 TreeMap This infographic clearly highlights their internal working, performance, ordering behavior, null handling, and real-world use cases. 💡 Key Takeaways: ✔️ HashMap Stores data using hashing (bucket structure) Provides O(1) average time complexity Does not maintain order Allows one null key and multiple null values Best for fast retrieval and general-purpose usage ✔️ LinkedHashMap Maintains insertion order using a linked structure Slight overhead compared to HashMap Supports predictable iteration order Commonly used in caching (LRU Cache implementation) ✔️ TreeMap Stores data in sorted order (Red-Black Tree) Provides O(log n) performance Does not allow null keys Supports natural ordering or custom Comparator Ideal for sorted data, range queries, and navigation ⚡ Key Insight: Choosing between these is not just about storing data — it’s about balancing performance, ordering, and business requirements. 🧠 This understanding helps in: Writing optimized backend logic Designing scalable systems Cracking Java & DSA interviews 📌 Consistency + Clarity = Growth #Java #CollectionsFramework #HashMap #LinkedHashMap #TreeMap #DataStructures #JavaDeveloper #BackendDevelopment #CodingJourney #LearnInPublic #SoftwareEngineering #DSA #TechCareers #Programming #Consistency
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 13/50 💡 Approach: Bidirectional HashMap Mapping One HashMap isn't enough here! If we only map s → t, we miss cases where two different characters in s map to the same character in t. The trick is to maintain mappings in BOTH directions simultaneously! 🔍 Key Insight: → Map every character of s to its corresponding character in t → Also map every character of t back to s → If either mapping is inconsistent at any point → return false → Both directions must agree throughout the string 📈 Complexity: ✅ Time: O(n) — single pass through both strings ✅ Space: O(1) — at most 256 unique ASCII characters in the maps Isomorphic strings taught me that in problem solving, perspective matters — always check both sides of the equation! 🔄 #LeetCode #DSA #HashMap #Java #ADA #PBL2 #LeetCodeChallenge #Day13of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #IsomorphicStrings
To view or add a comment, sign in
-
-
🚀 Ever wondered how a Set ensures only unique elements? 🤔 It’s not magic — it’s all about hashCode() and equals() working together. 🔹 How Set Avoids Duplicates When you add an element to a Set: ✔ First, hashCode() decides the bucket (location) ✔ Then, equals() checks if an identical object already exists ✔ If both match → ❌ Duplicate (not added) ✔ If not → ✅ Added successfully 💡 That’s why overriding both methods correctly is crucial! 🔸 Quick Example Insight If two objects have: ✔ Same hashCode() + equals() returns true → considered duplicate ✔ Different equals() → treated as unique 🔹 What About Hashtable? ✔ A synchronized Map (thread-safe) ✔ Does NOT allow null keys or values ✔ Slower due to synchronization 👉 Modern alternatives: HashMap (non-thread-safe) and ConcurrentHashMap (thread-safe & efficient) 💡 Key Takeaway: Set uses hashCode() + equals() to maintain uniqueness, while Hashtable focuses on thread-safe key-value storage. 🔥 Understanding internals = writing better Java code #Java #Collections #HashSet #Hashtable #OOP #JavaDeveloper #Programming #Coding #Tech #logics #DataStructures #JavaCollections #CodingInterview #SoftwareEngineering #DevelopersLife
To view or add a comment, sign in
-
-
🚀 Day 5/30 — LeetCode Challenge Solved Merge Two Sorted Lists on using Java. This problem focuses on pointer manipulation in linked lists — merging two sorted lists efficiently without creating extra space. ✅ Key takeaway: Understanding how to move and manage pointers is crucial when working with linked data structures. Time Complexity: O(n + m) Space Complexity: O(1) (in-place merge) Building consistency while strengthening fundamentals in data structures. #LeetCode #Java #LinkedList #DataStructures #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
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
-
-
𝐃𝐚𝐲 𝟖𝟑/𝟑𝟔𝟓 🚀 📌 𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐏𝐎𝐓𝐃: 𝐌𝐢𝐧𝐢𝐦𝐮𝐦 𝐃𝐢𝐬𝐭𝐚𝐧𝐜𝐞 𝐁𝐞𝐭𝐰𝐞𝐞𝐧 𝐓𝐡𝐫𝐞𝐞 𝐄𝐪𝐮𝐚𝐥 𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐬 𝐈𝐈 Continuing my 𝟑𝟔𝟓 𝐃𝐚𝐲𝐬 𝐨𝐟 𝐂𝐨𝐝𝐞 journey with a focus on 𝐩𝐫𝐨𝐛𝐥𝐞𝐦-𝐬𝐨𝐥𝐯𝐢𝐧𝐠, 𝐃𝐒𝐀, 𝐚𝐧𝐝 𝐜𝐨𝐧𝐬𝐢𝐬𝐭𝐞𝐧𝐜𝐲. 💪 🔎 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Store indices of each value using a HashMap. For values appearing at least 3 times, check consecutive triplets of indices. Compute distance using the formula: |i-j| + |j-k| + |i-k| Track the minimum distance. 🔍 𝐀𝐥𝐠𝐨𝐫𝐢𝐭𝐡𝐦 𝐮𝐬𝐞𝐝: HashMap + sliding window on index lists. ⏱ 𝐓𝐢𝐦𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: 𝐎(𝐧) 🧠 𝐒𝐩𝐚𝐜𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: 𝐎(𝐧) 📈 𝐊𝐞𝐲 𝐭𝐚𝐤𝐞𝐚𝐰𝐚𝐲: Grouping indices by value can drastically reduce complexity in duplicate-based problems. #LeetCode #LeetCodeDaily #365DaysOfCode #DSA #Java #HashMap #Arrays #Optimization #ProblemSolving #LearningInPublic 👨💻 🔗 Problem link in comments 👇
To view or add a comment, sign in
-
-
𝑯𝒂𝒔𝒉𝑴𝒂𝒑 𝒍𝒐𝒐𝒌𝒔 𝒔𝒊𝒎𝒑𝒍𝒆 𝒇𝒓𝒐𝒎 𝒐𝒖𝒕𝒔𝒊𝒅𝒆 𝑩𝒖𝒕 𝒊𝒏𝒕𝒆𝒓𝒏𝒂𝒍𝒍𝒚, 𝒕𝒉𝒆𝒓𝒆’𝒔 𝒂 𝒍𝒐𝒕 𝒉𝒂𝒑𝒑𝒆𝒏𝒊𝒏𝒈 𝒕𝒉𝒂𝒕 𝒎𝒐𝒔𝒕 𝒐𝒇 𝒖𝒔 𝒎𝒊𝒔𝒔 𝑾𝒆 𝒂𝒍𝒍 𝒖𝒔𝒆 𝑯𝒂𝒔𝒉𝑴𝒂𝒑 𝑩𝒖𝒕 𝒉𝒂𝒗𝒆 𝒚𝒐𝒖 𝒆𝒗𝒆𝒓 𝒕𝒓𝒊𝒆𝒅 𝒆𝒙𝒑𝒍𝒂𝒊𝒏𝒊𝒏𝒈 𝒊𝒕𝒔 𝒊𝒏𝒕𝒆𝒓𝒏𝒂𝒍 𝒘𝒐𝒓𝒌𝒊𝒏𝒈 𝒘𝒊𝒕𝒉𝒐𝒖𝒕 𝒈𝒆𝒕𝒕𝒊𝒏𝒈 𝒔𝒕𝒖𝒄𝒌 ? 🔍 𝐈𝐧𝐭𝐞𝐫𝐧𝐚𝐥 𝐖𝐨𝐫𝐤𝐢𝐧𝐠 𝐨𝐟 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 ➡️ 𝐖𝐡𝐞𝐧 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 𝐢𝐬 𝐜𝐫𝐞𝐚𝐭𝐞𝐝 ▪️An array of 16 buckets is created (default capacity) ▪️Each bucket acts like a LinkedList ➡️ 𝐖𝐡𝐞𝐧 𝐰𝐞 𝐢𝐧𝐬𝐞𝐫𝐭 (𝐤𝐞𝐲, 𝐯𝐚𝐥𝐮𝐞) map.put(key, value); 📃 Step 1: Hash Calculation ▪️ First, hashCode() is generated for the key 📃 Step 2: Index Calculation ▪️ Index is calculated using: index = (n - 1) & hashCode "n" = size of array (default 16) Result will be between 0 to 15 📃 Step 3: Storing in Bucket ▪️ This index decides which bucket to store data in ▪️Each bucket stores data as: (key, value) → (key, value) (LinkedList) 🔁 𝐖𝐡𝐚𝐭 𝐢𝐟 𝐛𝐮𝐜𝐤𝐞𝐭 𝐚𝐥𝐫𝐞𝐚𝐝𝐲 𝐡𝐚𝐬 𝐝𝐚𝐭𝐚(𝐂𝐨𝐥𝐥𝐢𝐬𝐢𝐨𝐧) ⛓️ HashMap checks for existing keys ▫️Uses equals() method ▫️Compares new key with existing keys ➡️ 𝐏𝐨𝐬𝐬𝐢𝐛𝐥𝐞 𝐂𝐚𝐬𝐞𝐬 : 1️⃣ If no key matches ▪️ New (key, value) is added 2️⃣ If key matches ▪️Old value is overridden ⚠️ 𝐈𝐦𝐩𝐨𝐫𝐭𝐚𝐧𝐭 𝐈𝐧𝐬𝐢𝐠𝐡𝐭 ➡️ A single bucket can hold multiple key-value pairs ➡️ Commonly up to 7 nodes in LinkedList, after that it may convert into a Tree (in newer Java versions) 🔄 𝐑𝐞𝐬𝐢𝐳𝐢𝐧𝐠 (𝐑𝐞𝐡𝐚𝐬𝐡𝐢𝐧𝐠) When 75% (3/4) of buckets are filled ▫️ Capacity increases from 16 → 32 ▫️ New array is created ▫️ All existing elements are rehashed & moved 🔖 𝐊𝐞𝐲 𝐏𝐨𝐢𝐧𝐭𝐬 ▫️ Default capacity → 16 ▫️ Uses LinkedList (or Tree in newer versions) ▫️ Uses equals() to compare keys ▫️ Uses bitwise AND for index calculation 💭 One Line Summary ➡️ HashMap is not random — it’s intelligently organized #Java #HashMap #JavaDeveloper #DataStructures #Programming #TechJourney #LearnBySharing #InterviewPrep #BackendDevelopment 🚀
To view or add a comment, sign in
-
HashMap Deep Dive (Beyond Basics) Most people use HashMap. Very few understand how it actually works internally. Key Concepts: - Array of Nodes (Bucket-based storage) - Hashing & Index calculation - Collision handling (LinkedList → Tree after threshold) - Load Factor & Rehashing - Time Complexity: - Average → O(1) - Worst → O(log n) (after Java 8) Interview-Level Insight Why Java 8 introduced Tree instead of LinkedList? How hashCode() & equals() impact performance? When does rehashing happen? Why initial capacity matters? Code Insight Map<Integer, String> map = new HashMap<>(); map.put(1, "A"); map.put(2, "B"); map.put(17, "C"); // Collision example (same bucket possible) // Internal flow: int hash = key.hashCode(); int index = (n - 1) & hash; Interview Gold If multiple keys land in the same bucket: - Before Java 8 → LinkedList (O(n)) - After Java 8 → Balanced Tree (O(log n)) This is a favorite interview discussion topic. Challenge for You Can you explain why HashMap is NOT thread-safe? What happens if two threads write simultaneously? Drop your answers below #Java #DSA #InterviewPreparation #SoftwareEngineering #CodingJourney #SystemDesign #Multithreading #JavaDeveloper
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
-
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