← Hash Strategies

Micro-Drill #241 — HashMap vs sorting for duplicates

Hash Strategies Target: 15s

HashMap = O(n) time, O(n) space. Sorting = O(n log n) time, O(1) space. Choose based on constraints.

HASHMAP vs SORTING FOR DUPLICATES
─────────────────────────────────
HASHMAP (Counter/set):
  + O(n) time
  + Preserves original order
  + Online: can process stream
  - O(n) extra space
  - Hash collisions (rare, but exist)

SORTING:
  + O(1) extra space (if in-place sort allowed)
  + Duplicates are adjacent → easy to skip
  + Natural for "kth largest" type problems
  - O(n log n) time
  - Destroys original order

DECISION:
  "Contains duplicate?"     → set, O(n)
  "Count occurrences?"      → Counter, O(n)
  "Find all duplicates?"    → Counter or sort
  "K most frequent?"        → Counter + heap
  "Remove duplicates?"      → set (unordered) or sort (ordered)
  "Group anagrams?"         → sorted string as key → HashMap

BOTH WORK for: two sum (hash O(n) vs sort O(n log n))
ONLY HASH for: subarray sum (prefix sum + hash)
ONLY SORT for: merge intervals, meeting rooms

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #240 Micro #242 →