Hash Maps: Membership, Frequency, Index Tracking

Work through examples, try the reasoning yourself, then put it into practice.

View Slides

Before you start

  • Trace a left-to-right scan and identify an element by its index.

What you will practice

  • Choose a set, count, or stored index from the requested answer.
  • Explain when a count is final and how to recover first-occurrence order.
In this lesson

Lesson

5 min read

Hash Maps and Frequency Counting

You have read [8,3] so far. The next value is 8. Can you answer “have I seen an 8?”, “how often?”, and “at which index?” from the same set of keys? All three questions can use 8 as a key. What you must store beside it depends on the answer the caller expects.

Return a pair of positions

Find two different positions totaling 11 in [5,8,1,3]. Trying every earlier partner works. At the final 3, every comparison asks the same question in disguise: which earlier position held 8? Store a position when you first have a chance to use it later.

Index and value Earlier value needed Result before recording this position
0 holds 5 6 Absent. Record 5 → 0.
1 holds 8 3 Absent. Record 8 → 1.
2 holds 1 10 Absent. Record 1 → 2.
3 holds 3 8 Found at 1. Return positions 1 and 3.

Immediately before reading index i, every stored position is smaller than i. Looking up the complement first makes reusing a position impossible. Storing the current number first would let a lone 5 pair with itself for target 10.

Try it. Compare [5,1] and [5,5] with target 10. Write both return values, then explain what goes wrong if a lookup at index zero is treated as a miss.

Check the lookup

The first input returns the pair (−1, −1). The second returns positions 0 and 1 in either order. At index 1 its lookup finds the earlier 5 at position 0. In Go, j, found := pos[need] gives both the stored index and its presence. In Python, need in pos checks presence even when the stored index is zero.

A Go map made with make(map[int]int) can accept the first assignment. A nil map can be read but a write panics. A set suffices for a yes/no pair question if you still check before inserting. For the index-returning task, retain a witness for each value. Practice Two Sum.

Decide whether two spellings use the same letters

A set gives the same answer for the letters in "aab" and "abb". Even the lengths agree. To decide whether rearrangement could turn one into the other, ask how many copies of each letter would remain after paying for the second spelling with letters from the first.

Step Balance of a Balance of b
Count all of "aab" 2 1
Consume a 1 1
Consume first b 1 0
Consume second b 1 −1

A deficit here is conclusive because the entire supply was counted first. With a different loop that reads one character from each string per step, a temporary deficit can be repaired. For "ba" and "ab", predict the two balances after each step before deciding when to check them.

Check the timing

After the first step a has balance −1 and b has +1. After the second, both have zero. With this update order, test all balances at the end. Zero for every letter means every occurrence can be matched.

The exercise promises lowercase English letters. A table with 26 counters is enough. A dictionary of counts also works and uses one entry per distinct key encountered. Both scan the input once with O(1) additional space for this fixed alphabet. Practice Valid Anagram.

Find the first unique character

Consider "swiss". The initial s looks unique until another s arrives. Counting the entire word gives s → 3, w → 1, i → 1. Now which of w and i came first? Scan the original positions again. At 0 the count for s rules it out. At 1 the count for w is one, so return 1. Scanning a 26-slot count table in alphabetic order would choose i and give a different answer.

Try it. Which index do you return for "zabza", "zz", and the empty string? If all characters were distinct, how much of the input would you still need to inspect before declaring index 0 unique?

Check the order

In "zabza", b at index 2 is the only singleton. The other two inputs have no singleton and return −1. Even if the first character really is unique, the last unread character could repeat it. Finish establishing the counts before choosing the earliest qualifying index.

A Go map can enumerate keys in different orders. Python dictionaries preserve insertion order, but both languages can express this decision directly by scanning the original input. Practice First Unique Character.

Count the work and change the question

Checking every earlier index can take n(n−1)/2 comparisons. With integer keys, one map lookup and at most one insertion per input position give expected O(n) time under the usual hashing assumption. Growing the table can make an individual insertion expensive; amortized cost spreads that growth over many insertions. The position map uses O(d) entries for d distinct values. Hashing an entire string can also cost time proportional to its length.

Now change Two Sum. For [4,4,4], target 8, return the number of index pairs. Try answering with just the latest position of 4. What information would make each new position's contribution visible?

Check your design

Position 1 can pair with one earlier 4. Position 2 can pair with two. A frequency beside each key lets you add those contributions to get 3. Look up the earlier count before incrementing it so each pair is counted once. The original exercise still asks for two positions.

Test your reasoning in the hash map checkpoint.


Practice sequence

Use the order below for a guided path, or choose an item to revisit. A pass records a successful attempt; try a fresh example later to check what you can reconstruct.

Join Discord