sagelearnai

Arrays & Hashing

Signal: "find a duplicate", "have we seen X before?", "count occurrences", "group things that are equivalent", or any brute force that looks like for each element, scan all others.

Core idea: a hash set or hash map gives average O(1) insert and lookup, so a nested O(n²) scan becomes a single O(n) pass that remembers what it has seen. The price is O(n) extra memory.

Brute force O(n²)for i in range(n): for j in range(i+1, n): compare(a[i], a[j]) Hash map O(n)seen = {}for x in a: check seen, then add xeach lookup is O(1) on average

Templates

python
# 1) Seen-before check
seen = set()
for x in nums:
    if x in seen:            # O(1) average
        ...                  # found a repeat / complement
    seen.add(x)

# 2) Frequency counting
from collections import Counter
freq = Counter(nums)         # {value: count}

# 3) Grouping by a canonical key
from collections import defaultdict
groups = defaultdict(list)
for item in items:
    groups[canonical(item)].append(item)

Choosing the key

The trick in many problems is the canonical key: sorted letters for anagrams, a (dx, dy) slope for collinear points, a tuple of counts. Ask yourself: what do all equivalent items have in common, and how can I make it hashable?

Interview tip

Mention the trade-off out loud: "I'll use O(n) extra memory to get O(n) time. If memory were tight, I could sort in place for O(n log n) and O(1) extra space."

Problems

  1. Two Sum (Easy): Store value → index, look up complement
  2. Contains Duplicate (Easy): Hash set of seen values
  3. Valid Anagram (Easy): Compare character counts
  4. Ransom Note (Easy): Letter counts of magazine must cover the note
  5. Isomorphic Strings (Easy): Two maps enforce a one-to-one character mapping
  6. Group Anagrams (Medium): Canonical key = sorted letters (or letter counts)
  7. Top K Frequent Elements (Medium): Count, then bucket by frequency
  8. Longest Consecutive Sequence (Medium): Only start counting at sequence starts (x−1 absent)
  9. Majority Element (Easy): Boyer–Moore voting
  10. First Unique Character in a String (Easy): Count, then scan for the first count of 1
  11. Word Pattern (Easy): Bijection between letters and words
  12. Longest Palindrome (Easy): Use all even counts; one odd count can sit in the middle
  13. Find All Numbers Disappeared in an Array (Easy): Mark seen values by negating nums[value−1]
  14. 4Sum II (Medium): Count pair sums of A+B, look up −(C+D)
  15. Insert Delete GetRandom O(1) (Medium): Array of values + map value→index; swap-with-last to delete
  16. Majority Element II (Medium): Boyer–Moore with two candidates, then verify
  17. Encode and Decode Strings (Medium): Length-prefix each string: "len#string"