LLD Data Structures in Design Context: How Does a HashMap Find the Right Location? Understanding Hashing Without the Math
"The real magic of a HashMap isn't that it stores data. It's that it knows where to start looking." In the previous article, we learned that a HashMap organises information around unique keys. Instead of searching every stored object one by one, it uses the key to retrieve information quickly. That naturally raises another question. "If millions of objects are stored inside a HashMap, how does it know where to begin?" Surely it isn't remembering the location of every object individually. The answer lies in one of the most important ideas in computer science: Hashing. Don't worry if the word sounds intimidating. Despite its name, the idea behind hashing is surprisingly simple. Imagine a Huge Apartment Building Suppose you're visiting a friend who lives in a building with 5,000 apartments. If nobody told you the apartment number, what would you do? Probably something like this. Apartment 1 ↓ Apartment 2 ↓ Apartment 3 ↓ ... ↓ Friend's Apartment That would take a long time. Now imagine your friend simply tells you: Apartment 1842 Suddenly, you don't search the building. You walk directly to Apartment 1842. The apartment number isn't your friend. It simply tells you where to begin. Hashing works in exactly the same way. Keys Need Locations Suppose our application stores customers. Customer ID → Customer 1001 → Alice 1002 → Bob 1003 → Charlie 1004 → David The system needs a way to answer one question. "Where should Customer 1002 be stored?" Searching every location first would defeat the purpose of using a HashMap. Instead, the system calculates where that key should go. Notice something important. It doesn't compare Customer 1002 against every other customer. It calculates a location directly. Think of a School Locker System Imagine a school with thousands of students. Every student receives a locker. Student ID ↓ Locker Number ↓ Locker Students don't spend every morning searching hundreds of lockers. Their Student ID determines where they should go. The locker number is