Hash sets and hash maps

Hash sets and hash maps

Before the problems, let's get comfortable with the one tool this whole section leans on: the hash map.

Counting with a map

A hash map stores key-value pairs and looks up, inserts, and updates any key in constant time. To count occurrences, increment the count for each key as you see it — the count for "apple" starts at 0, becomes 3, then 4 on the next increment. Because a missing key can be treated as having a count of zero, counting stays clean: there's no need to check "have I seen this key yet?" before incrementing it. Walking through "banana" letter by letter, the first 'a' reads as 0 and becomes 1, the second 'a' reads as 1 and becomes 2, and so on.

Using a map as a set

A hash set is a map whose values carry no real information — only membership matters. Insert a key when you see it, then ask the set whether it contains a given key later. That membership check is constant time, which is what makes sets so useful for "have I seen this before?" problems.

Telling "absent" from "present with a default value"

Sometimes it matters whether a key was ever inserted at all, not just what value it holds. Most hash map implementations offer a way to check for a key's presence directly, separate from reading its value — use that when a missing key and a zero-valued key need to mean different things.

Iteration order isn't guaranteed

Walking over a hash map's entries generally visits them in an unspecified order that shouldn't be relied on. When a problem needs sorted output, collect the keys into a list and sort them explicitly — never rely on the map's natural order. Most problems in this section ask for sorted results for exactly this reason: it keeps the answer deterministic.

Three moves cover every problem in this section: count by incrementing a map entry, test membership with a set or map, and sort keys when order matters.