← All Comparisons
Hash Map Counting vs Two Sum Pattern
Quick Answer
Use Hash Map Counting when you need to track how many times each element appears (anagrams, majority element, frequency-based grouping). Use Two Sum Pattern when you need to find pairs that sum to a target or satisfy a complement relationship (two sum, three sum, valid anagram with complement check).
Side-by-Side Comparison
| Aspect | Hash Map Counting | Two Sum Pattern |
|---|---|---|
| Primary use | Store and query element frequencies | Store seen values to find complements |
| Key in map | Element (or derived key) | Value or complement (target - current) |
| Value in map | Count (integer) | Index or count (depending on problem) |
| Typical question | How many times does X appear? What is the most frequent? | Does a complement exist? Find indices that sum to target. |
| Pass structure | Build full map first, then query or compare | Single pass: check complement before adding current |
| When optimal | Anagrams, majority element, group by frequency | Pair finding, subarray sum, complement-based validation |
| Time complexity | O(n) for build + O(n) for processing | O(n) single pass |
Decision Framework
- Does the problem ask for "how many" of each element, or "most frequent"? Use Hash Map Counting.
- Does the problem ask for pairs that sum to target, or "does complement exist"? Use Two Sum Pattern.
- Do you need to compare two collections (e.g., anagram: same chars, same counts)? Count both, then compare maps.
- Do you need to find a pair in one pass without pre-building? Two Sum: store seen, check target - current.
- Is it a subarray sum problem (contiguous sum = k)? Prefix sum + Two Sum (store prefix sums, look for complement).
- Is it grouping or partitioning by value? Hash Map Counting.
Example Problems
Hash Map Counting
- 1.Valid Anagram — Count chars in both strings, compare maps.
- 2.Majority Element — Count frequencies, find element with count > n/2.
- 3.Group Anagrams — Use sorted string or char count as key; group by frequency signature.
- 4.Top K Frequent Elements — Count frequencies, then bucket or heap by count.
Two Sum Pattern
- 1.Two Sum — Store seen values; for each num, check if target - num exists.
- 2.Subarray Sum Equals K — Prefix sum + map: count prefix sums, look for currPrefix - k.
- 3.3Sum — Fix one element, then two-sum on the rest for complement.
- 4.Two Sum IV (BST) — In-order traversal + two sum: store seen, check complement.