Ever called map.get("Key1") on a HashMap and wondered what really happens behind the scenes? I did too, and it’s surprisingly cool. Here’s a quick breakdown of what goes on internally: → First, the key’s hashCode() is calculated to decide *where* the entry should live in memory. → Next, the index is computed (something like hashCode & (arrayLength - 1)). → If multiple keys end up at the same spot (collision), HashMap handles it using a linked list, or even a tree (from Java 8 onward) when things get heavy. → Finally, equals() is used to confirm we’ve got the exact key before returning the value. Important takeaway: if you override hashCode(), always override equals() too, they’re a package deal! Fun fact: a bad hashCode() can make your map sluggish, even with few entries. Have you ever implemented your own custom key class? #Java #HashMap #CodingTips #Developers #100DaysOfCode #LearnWithNayan Credits: https://lnkd.in/dK9deahF
How HashMap works: A deep dive into the code
More Relevant Posts
-
LeetCode Question #199 — Binary Tree Right Side View Thrilled to share another Accepted Solution (100% Runtime 🚀) on LeetCode! This problem focuses on Binary Trees — specifically, how to capture the view of a tree from its right side 🌳➡️. I implemented a Modified Pre-Order Traversal (Root → Right → Left) in Java, ensuring that the first node at each level (from the right) gets recorded. 💡 Key Idea: Use recursion with a level tracker — when the current level equals the list size, it means we’re seeing the rightmost node for the first time. Here’s the performance snapshot: ⚙️ Runtime: 0 ms (Beats 100% of Java submissions) 💾 Memory: 42.4 MB Every problem like this sharpens my understanding of tree traversal patterns and depth-first search optimization. #LeetCode #Java #DataStructures #BinaryTree #ProblemSolving #CodingJourney #DSA #100PercentRuntime
To view or add a comment, sign in
-
-
Day 80 of #100DaysOfCode Solved Frequency Sort in Java 🔠 Approach Today's problem was to sort an array based on the frequency of its numbers. My initial solution was accepted, but it exposed a major efficiency gap! My strategy involved: Sorting the array first. Using nested loops to count the frequency of each number and store it in a HashMap. (Implied) Using the counts to perform the final custom sort. The core issue was the counting method: running a full loop inside another full loop to get the frequency. This quadratic $O(N^2)$ counting completely tanked the performance. ✅ Runtime: 29 ms (Beats 12.02%) ✅ Memory: 45.26 MB (Beats 5.86%) Another great lesson in algorithmic complexity! The difference between $O(N^2)$ and the optimal $O(N \log N)$ for this problem is massive. Time to refactor and implement the fast, single-pass $O(N)$ frequency count using getOrDefault! 💪 #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #HashMap #Optimization #ProblemSolving
To view or add a comment, sign in
-
-
💻 Day 52 of #100DaysOfCodeChallenge Today’s problem: LeetCode 203 – Remove Linked List Elements 🧩 I worked on a Linked List manipulation problem where the goal is to remove all nodes that match a given value. This problem helped strengthen my understanding of pointer handling and dummy node usage in linked lists. 🧠 What I Learned: Handling edge cases where the head itself might need to be removed. Using a dummy node before the head to simplify pointer operations. How current and next pointers work together to modify a linked list safely. 🧩 Java Solution: class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while (current.next != null) { if (current.next.val == val) current.next = current.next.next; else current = current.next; } return dummy.next; } } ⏱️ Complexity: Time: O(n) Space: O(1) Every day, I’m getting more confident with data structures and linked list traversal logic. On to the next challenge 🚀 #Day52 #LeetCode #Java #100DaysOfCode #CodingChallenge #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
🚀 LeetCode #58 – Length of Last Word (Java Solution) Today I solved a classic string problem that tests how well you handle edge cases and string traversal logic. 🧩 Problem Statement: Given a string s consisting of words and spaces, return the length of the last word in the string. A word is defined as a maximal substring consisting of non-space characters only. 🧠 Dry Run Example Input: " fly me to the moon " ➡ After skipping spaces → "fly me to the moon" ➡ Last word = "moon" ➡ Output: 4 ⚙️ Time & Space Complexity Time Complexity: O(n) — we traverse the string once (from the end to the start). Space Complexity: O(1) — no extra space used apart from a few variables. 💡 Key Takeaways: ✅ Learned how to handle trailing spaces properly before counting. ✅ Strengthened understanding of string traversal in reverse. ✅ Explored an alternative approach using trim() + split("\\s+") for readability. ✅ Remembered to test with edge cases like "a" or "Hello " to ensure correctness. Every small problem like this helps in building stronger fundamentals 💪 #Java #LeetCode #ProblemSolving #CodingJourney #LearningInPublic #75DaysOfCode #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🪲 🔥 Most bugs don’t live in your HashMap — they live in your equals() and hashCode(). Every Java developer uses HashMap almost every day — but very few know what really happens inside it. We just call put() and move on… but under the hood, something interesting (and sometimes scary) happens. When you add a key-value pair, Java uses the key’s hashCode() to decide where that entry will live. If two different keys have the same hash code, they end up in the same bucket — this is called a collision. Now the real test begins. Java uses equals() to check if the new key is actually the same as the existing one. If both methods (equals() and hashCode()) don’t agree, HashMap gets confused. Your data might vanish, overwrite another entry, or behave unpredictably. That’s why overriding both methods properly is more than just a best practice — it’s the difference between clean code and mysterious bugs. So next time your map “acts weird,” remember — it’s not the HashMap’s fault. It’s a silent war between equals() and hashCode(). #Java #HashMap #SpringBoot #CleanCode #CodingLife #Microservices #SoftwareEngineering #DevelopersLife
To view or add a comment, sign in
-
-
Day 39/100 – #100DaysOfCode 🚀 | #Java #LeetCode #HashMap ✅ Problem Solved: Minimum Index Sum of Two Lists 🧩 Problem Summary: Given two string arrays, find the common strings with the smallest index sum (index in list1 + index in list2). If multiple answers exist, return all of them. 💡 Approach Used: ➤ Stored the elements of the first list in a HashMap with their indices. ➤ Iterated the second list and checked for matches. ➤ Tracked the minimum index sum and collected all strings that match that sum. This avoids nested loops and improves efficiency. ⚙️ Time Complexity: O(n + m) 📦 Space Complexity: O(n) ✨ Takeaway: HashMaps continue to be one of the most effective tools for reducing time complexity through direct lookups 🔍⚡ #Java #LeetCode #HashMap #DataStructures #ProblemSolving #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙️ Complexity: ⏱️ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge
To view or add a comment, sign in
-
-
✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙️ Complexity: ⏱️ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge
To view or add a comment, sign in
-
-
Today, I explored the Stack class in Java — a data structure that follows the LIFO (Last In, First Out) principle. Here's what I practiced 👇 🧱 Key Stack Methods: push() → Adds an element to the top of the stack. pop() → Removes and returns the top element. peek() → Returns (but doesn’t remove) the top element. empty() → Checks if the stack is empty. search() → Returns the position of an element from the top (1-based index). 🧑💻 Output shows how each operation works in real-time — from adding elements to removing and peeking at the top! #Java #CollectionsFramework #Stack #CodingJourney #LearningJava #FullStackDeveloper
To view or add a comment, sign in
-
-
🎯 Day 62 of #100DaysOfLeetCode Today I solved the “Merge Two Sorted Lists” problem using Java This problem is a great exercise in understanding how to work with Linked Lists and pointer manipulation. The goal is to merge two sorted linked lists into one sorted list — without using extra space for another list. Key Concepts Practiced: Linked List traversal Dummy node technique Efficient merging using pointers Handling null edge cases Approach Summary: Create a dummy node to simplify edge cases. Use two pointers to traverse both lists. Compare values and link nodes in sorted order. Attach any remaining nodes at the end. #100DaysOfCode #LeetCode #Java #CodingChallenge #DataStructures #LinkedList #ProblemSolving #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