Hash Map Patterns: Two Sum, Frequency Counters & Subarray Sums
Hash Map Patterns: Two Sum, Frequency Counters & Subarray Sums
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.
1. Real-World Analogy: The Detective's Suspect Board
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.
2. Pattern 1: Unsorted Two Sum ($O(n)$ Time, $O(n)$ Space)
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:
Modern JavaScript / TypeScript:
3. Pattern 2: Frequency Counters & Valid Anagrams
Determine if string t is an anagram of string s (contains the exact same characters with identical counts):
4. Pattern 3: Subarray Sum Equals K (Prefix Sum + Hash Map)
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 equaledcurr_sum - k. - Storing prefix sum frequencies in a Hash Map unlocks an $O(n)$ solution for negative and positive numbers alike!
5. Trace Table: Two Sum on nums = [2, 11, 7, 15], target = 9
| Index ($i$) | nums[i] | complement = 9 - nums[i] | In seen Map? | Action | seen Map State |
|---|---|---|---|---|---|
| 0 | 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!
Multiple Choice Questions
{0: 1}?{}) as hash maps when keys are arbitrary objects or when prototype pollution is a security risk?Recursion Fundamentals: Base Cases, Recursive Leaps & Call Stack Visuals
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.