Skip to content
← 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

AspectHash Map CountingTwo Sum Pattern
Primary useStore and query element frequenciesStore seen values to find complements
Key in mapElement (or derived key)Value or complement (target - current)
Value in mapCount (integer)Index or count (depending on problem)
Typical questionHow many times does X appear? What is the most frequent?Does a complement exist? Find indices that sum to target.
Pass structureBuild full map first, then query or compareSingle pass: check complement before adding current
When optimalAnagrams, majority element, group by frequencyPair finding, subarray sum, complement-based validation
Time complexityO(n) for build + O(n) for processingO(n) single pass

Decision Framework

  1. Does the problem ask for "how many" of each element, or "most frequent"? Use Hash Map Counting.
  2. Does the problem ask for pairs that sum to target, or "does complement exist"? Use Two Sum Pattern.
  3. Do you need to compare two collections (e.g., anagram: same chars, same counts)? Count both, then compare maps.
  4. Do you need to find a pair in one pass without pre-building? Two Sum: store seen, check target - current.
  5. Is it a subarray sum problem (contiguous sum = k)? Prefix sum + Two Sum (store prefix sums, look for complement).
  6. 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.