Core Module
12 min forge
HashMaps & Dictionaries
Master the most versatile data structure for constant-time lookups, inserts, and deletions.
πΊοΈ HashMaps: Constant Time Mastery
A HashMap (or Object/Map in JavaScript) is a data structure that stores data in key-value pairs. It uses a hash function to compute an index into an array of buckets, from which the desired value can be found.
π‘ The Logic (ELI5)
Think of a HashMap as a massive array of numbered cubbies, but instead of using a number to find your cubby, you use a Name:
- You want to store your "Blue Shirt" in a cubby named "Outfit".
- The "Magic Blender" (Hash Function) takes the word "Outfit" and turns it into a number, say 42.
- You put the "Blue Shirt" in cubby 42.
- Next time you want your "Outfit", you give the Blender the name "Outfit", it gives you 42 again, and you go straight to the shirt!
π The Deep Dive
Core Properties
- Key-Value Storage: Every item has a unique identifier (key).
- Complexity: $O(1)$ average time for Put, Get, and Remove.
- Hashing: The process of converting a key into an integer index.
- Collisions: When two different keys produce the same index. Handled via Chaining (linked lists in buckets) or Open Addressing.
Use Cases
- Caching: Storing results of expensive operations.
- Counting: Tracking occurrences of items.
- Indexing: Mapping IDs to full objects for fast access.
- Two Sum: Reducing $O(n^2)$ search to $O(n)$.
π οΈ Code Forge: Map Operations
javascript Standard/** * Using the native JavaScript Map object */ const userMap = new Map(); // 1. Setting Values userMap.set('id_101', { name: 'Alice', role: 'Engineer' }); userMap.set('id_102', { name: 'Bob', role: 'Designer' }); // 2. Getting Values (O(1)) const user = userMap.get('id_101'); console.log(user.name); // Alice // 3. Checking Existence if (userMap.has('id_101')) { console.log("User exists!"); } // 4. Deleting userMap.delete('id_102'); // 5. Size console.log(userMap.size); // 1
π― Interview Pulse
Map vs. Object in JS
- Map: Better for frequent additions/removals, supports any data type as key, maintains insertion order.
- Object: Better for simple records, only supports strings/symbols as keys, slightly more overhead for dynamic hashing.
Common Interview Questions
- Two Sum: Use a map to store
target - currentand find matches in one pass. - LRU Cache: A classic high-level design problem using a Map and a Doubly Linked List.
- Isomorphic Strings: Using two maps to check mapping consistency.