SproutStackSproutStack home

Hash Tables & Counting

6 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

A cloakroom for values

A hash table is a cloakroom: hand over your coat (key), get a ticket (hash), retrieve it in O(1) average time. Python dicts, Java HashMaps, JavaScript objects — same idea, different uniforms. The superpower for interviews: remembering what you've already seen so you never rescan.

Two Sum: the poster child

"Find two numbers summing to target" — brute force checks every pair (O(n²)). The insight: for each x, the partner you need is target − x. Seen it before? Done. Otherwise file x away and move on:

def two_sum(a, t):
    m = {}
    for i, x in enumerate(a):
        if t - x in m:            # partner already checked in?
            return [m[t - x], i]
        m[x] = i                  # else leave your ticket

One pass, O(n) time, O(n) space. The pattern generalizes: complement lookup also cracks 3Sum-adjacent problems, pair counting, and subarray-sum variants.

The counting family

  • Frequency maps: "first unique character," "ransom note" — count with Counter, then decide.
  • Anagrams: Counter(s) == Counter(t) — same letters, same counts, done. (Sorting works too but costs O(n log n) for showmanship points you don't need.)
  • Grouping: anagrams together? File each word under its sorted key in a dict of lists.

What can be a key

Keys must not change after they are stored, because the table files them by their hash. In Python that means strings, numbers, and tuples work, while lists and dicts raise TypeError: unhashable type. When you need a composite key, use a tuple: grouping anagrams by tuple(sorted(word)), or storing grid positions as (row, col).

Set or map?

  • Use a set when you only need to know whether something has been seen: "contains duplicate," "visited cells."
  • Use a map when each key needs an attached value: an index (Two Sum), a count (frequencies), or a list (grouping).

Choosing the simpler one makes the code shorter and your intent obvious.

A worked example: first unique character

Find the first character in "leetcode" that appears only once.

  1. Count. One pass builds the counts: l:1, e:3, t:1, c:1, o:1, d:1.
  2. Scan in order. A second pass walks the string from the start and returns the first character whose count is 1. That is "l", at position 0.

Two passes of O(n) each is still O(n). Trying to decide during the first pass fails, because when you see the first "e" you cannot yet know that two more are coming.

Collisions, in one paragraph

Two keys can draw the same ticket — handled by chaining (a mini-list per ticket) or open addressing (take the next free spot). Interviews almost never go deeper, but knowing the word "chaining" keeps you safe. Average O(1) holds as long as the table resizes; pathological worst case degrades to O(n).

Space is the price

A hash map buys speed with memory: O(n) extra space to remember n items. Usually that is the right trade. When an interviewer adds "now use constant extra space," the usual alternative is to sort first and use two pointers, accepting O(n log n) time in exchange for O(1) extra space. Naming that trade out loud is often exactly the answer they are looking for.

Remember this

  • Seen-it-before problems → hash map. Counting problems → Counter.
  • Two Sum's complement trick unlocks a whole problem family.

Check your understanding

5 questions · first-try answers earn the most XP

1. You are solving Two Sum and have already seen the values 3 and 7. The current value is x and the target is t. What should you look up?
2. A hash map lookup returns nothing for a key you just inserted. What is the most likely explanation?
3. What makes a hash table lookup average-case O(1)?
4. In frequency counting with a map, why do you usually scan the map afterwards rather than during the loop?
5. Why can a hash map's worst case degrade to O(n)?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Practice this pattern elsewhere

More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.