Hash Strategies
Hash map for associations, hash set for membership, sorting when you can afford O(n log n) and want O(1) space.
HASH MAP vs SET vs SORTING
───────────────────────────
HASH MAP (dict) — need value association:
□ Count occurrences → Counter / defaultdict(int)
□ Two sum: complement lookup → {val: index}
□ Group anagrams → {sorted_key: [words]}
□ Prefix sum → {running_sum: count}
Time: O(1) avg lookup, O(n) space
HASH SET — need membership only:
□ Contains duplicate → set(nums)
□ Intersection of arrays → set1 & set2
□ Visited tracking → seen = set()
□ Cycle detection (Floyd's is O(1) space alt)
Time: O(1) avg lookup, O(n) space
SORTING — when order matters:
□ Two pointer after sort → O(n log n)
□ Merge intervals → sort by start
□ Meeting rooms → sort events
□ No extra space needed
Time: O(n log n), O(1) extra space
DECISION:
Need key→value? → hash map
Need "seen before"? → hash set
Need O(1) space? → sort (if O(n log n) OK)
Need to preserve order? → hash map (not sort)
Streaming / online? → hash (sort needs all data)