Hash maps are the single most effective tool for transforming sluggish brute-force $O(n^2)$ solutions into $O(n)$ linear time . By caching values in memory for instant $O(1)$ lookup, hash map patterns conquer interview classics: Frequency Counters , Unsorted Two Sum , and Subarray Sum Equals K .
Imagine a detective looking for two puzzle pieces that combine to equal a target clue:
Brute Force: Pick Piece 1, compare it against all other 10,000 pieces. Repeat for Piece 2, Piece 3 ($10,000^2$ comparisons). Hash Map Look-Back Pattern: When inspecting Piece $X$, calculate what piece you need: $\text{Complement} = \text{Target} - X$. Check your detective notebook (Hash Map ): "Have I already seen the Complement?" If yes, you found the pair instantly! If no, write $X$ in your notebook and move to the next piece. Given an unsorted array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Python 3 Implementation: 1 def two_sum ( nums : list [ int ] , target : int ) - > list [ int ] :
2 seen = { } # Maps value -> index
3
4 for i , num in enumerate ( nums ) :
5 complement = target - num
6 if complement in seen :
7 return [ seen [ complement ] , i ]
8 seen [ num ] = i
9
10 return [ ]
Modern JavaScript / TypeScript: 1 export function twoSum ( nums : number [ ] , target : number ) : number [ ] {
2 const seen = new Map < number , number > ( ) ; // value -> index
3
4 for ( let i = 0 ; i < nums . length ; i ++ ) {
5 const complement = target - nums [ i ] ;
6 if ( seen . has ( complement ) ) {
7 return [ seen . get ( complement ) ! , i ] ;
8 }
9 seen . set ( nums [ i ] , i ) ;
10 }
11
12 return [ ] ;
13 }
Determine if string t is an anagram of string s (contains the exact same characters with identical counts):
1 def is_anagram ( s : str , t : str ) - > bool :
2 if len ( s ) != len ( t ) :
3 return False
4
5 counts = { }
6 for char in s :
7 counts [ char ] = counts . get ( char , 0 ) + 1
8
9 for char in t :
10 if char not in counts or counts [ char ] == 0 :
11 return False
12 counts [ char ] -= 1
13
14 return True
Find the total number of continuous subarrays whose sum equals k:
As we maintain a running prefix sum curr_sum, we need to know how many previous prefix sums equaled curr_sum - k. Storing prefix sum frequencies in a Hash Map unlocks an $O(n)$ solution for negative and positive numbers alike! 1 def subarray_sum_equals_k ( nums : list [ int ] , k : int ) - > int :
2 prefix_counts = { 0 : 1 } # Base case: a prefix sum of 0 has occurred once
3 curr_sum = 0
4 total_subarrays = 0
5
6 for num in nums :
7 curr_sum += num
8 # If (curr_sum - k) exists in map, we found valid subarrays!
9 if ( curr_sum - k ) in prefix_counts :
10 total_subarrays += prefix_counts [ curr_sum - k ]
11
12 prefix_counts [ curr_sum ] = prefix_counts . get ( curr_sum , 0 ) + 1
13
14 return total_subarrays
Index ($i$) nums[i]complement = 9 - nums[i]In seen Map? Action seen Map State0 2 7 No Store {2: 0} {2: 0}1 11 -2 No Store {11: 1} {2: 0, 11: 1}2 7 2 Yes! (index 0) Return [0, 2] Pair Found!
Result: Returned [0, 2] in a single pass of 3 steps!
Interactive Quiz • Knowledge Check
Multiple Choice Questions How does using a Hash Map reduce the Two Sum problem from $O(n^2)$ to $O(n)$?
A It sorts the array automatically.
B It allows checking whether the required complement (target - num) has been seen previously in $O(1)$ time during a single linear traversal.
C It divides the array in half using binary search.
D It deletes duplicate numbers.
In the "Subarray Sum Equals K" problem, why must the prefix sum map be initialized with {0: 1}?
A To prevent division by zero errors.
B To account for subarrays that start at index 0 whose sum directly equals $k$ without needing a prior subtraction.
C Because all hash maps require at least one key.
D To sort the prefix sums.
What is the time complexity of verifying if two strings of length $n$ are anagrams using a Frequency Counter hash table?
A $O(n^2)$
B $O(n)$
C $O(\log n)$
D $O(2^n)$
What is the space-time tradeoff of the Hash Map Two Sum approach compared to the Two-Pointer approach on an unsorted array?
A Hash Map uses $O(1)$ space; Two Pointers uses $O(n)$ space.
B Hash Map achieves $O(n)$ time with $O(n)$ auxiliary space, whereas sorting the array for Two Pointers takes $O(n \log n)$ time but can use $O(1)$ space.
C Two Pointers runs in $O(n^3)$ time.
D Hash Map only works on positive numbers.
Why should you avoid using plain JavaScript objects ({}) as hash maps when keys are arbitrary objects or when prototype pollution is a security risk?
A Plain objects cannot store strings.
B Plain JavaScript objects inherit built-in prototype keys (like toString, valueOf) and only support string/symbol keys; Map supports any key type and avoids prototype pollution.
C Map runs on the GPU.
D Plain objects do not support JSON serialization.