Hash Table
Welcome to the Hash Table section of JDCodebase! Hash Tables (or objects/maps in JavaScript) allow you to store and access data in constant time. They're essential for solving problems that involve frequency counting, lookups, memoization, and fast data association.
What You’ll Learn
- Use maps or objects for constant-time lookups
- Count frequency of elements in arrays or strings
- Store indices, track visited elements or unique entries
- Avoid nested loops by caching results in key-value form
- Optimize brute force logic using hash-based storage
JavaScript Hash Table Methods
const map = new Map(): Creates a new Map object for key-value storage.
Before: Code: const map = new Map(); After: An empty map is ready to use.
map.set(key, value): Adds or updates an entry in the map.
Before: Map is empty Code: map.set("a", 1); After: Map now contains: {"a" => 1}
map.get(key): Retrieves the value for a given key.
Before: {"a" => 1} Code: map.get("a"); After: 1
map.has(key): Checks if the map contains the key.
Before: {"a" => 1} Code: map.has("a"); After: true
map.delete(key): Removes the key-value pair from the map.
Before: {"a" => 1} Code: map.delete("a"); After: Map is now empty
Object literals as hash tables: Use `{}` for quick frequency counts.
Before: str = 'aabbc' Code: const freq = {}; for (let char of str) { freq[char] = (freq[char] || 0) + 1; } After: { a: 2, b: 2, c: 1 }
const set = new Set(): Creates a new Set that stores unique values.
Before: Code: const set = new Set(); After: An empty Set is created.
set.add(value): Adds a unique value to the Set.
Before: Set is empty Code: set.add(5); set.add(5); After: Set contains: {5} (duplicates ignored)
set.has(value): Checks if a value exists in the Set.
Before: Set contains: {5} Code: set.has(5); After: true
set.delete(value): Removes a value from the Set if present.
Before: Set contains: {5} Code: set.delete(5); After: Set is now empty
set.size: Returns the number of unique values in the Set.
Before: Set contains: {1, 2, 3} Code: set.size; After: 3
Try This Example
Check if two strings are anagrams using hash maps.
function isAnagram(s, t) { if (s.length !== t.length) return false; const count = {}; for (let char of s) { count[char] = (count[char] || 0) + 1; } for (let char of t) { if (!count[char]) return false; count[char]--; } return true; }
Input: s = "listen", t = "silent"
Expected Output: true