Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Hashing and identity
EXPERIMENT 13 / 66

Count what matters.

Use dictionaries and Counter for grouping and lookup without repeated scans.

BY NAVAN SAMI◷ 7 MIN READSTARTERSTRUCTURE

01 Model the idea

A hash map associates keys with values and supports expected constant-time access under normal assumptions. A frequency table uses each distinct observation as a key and stores how often it appears. collections.Counter expresses that pattern directly. Hashable keys must remain compatible with their hash and equality semantics while stored in a mapping.

THE THING THAT MUST STAY TRUE

Each count equals the number of matching observations processed so far.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
FOR each observation
  normalise its key
  increment that key’s count
REPORT keys in a deliberate order

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

hash_maps.py
from collections import Counter
states = ["open", "done", "open", "blocked", "done", "open"]
counts = Counter(states)
for state in sorted(counts):
    print(state, counts[state])
print("missing:", counts["unknown"])
↳ EXPECTED OUTPUT
blocked 1
done 2
open 3
missing: 0
  1. 1

    Counter consumes the observations and accumulates counts. Sorting keys makes this report deterministic.

  2. 2

    A missing Counter key reads as zero. Ordinary dictionaries instead raise KeyError when accessed with brackets and no such key exists.

  3. 3

    Hash collisions can affect performance, and key equality affects grouping. Normalise text deliberately if "Open" and "open" should count as the same application state.

04 Count the cost

TIME

Expected O(n) counting plus O(u log u) to sort u distinct keys

SPACE

O(u) counts for u distinct keys

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Count words case-insensitively and print the count for build.

Reveal one possible solution +
one_possible_solution.py
from collections import Counter
words = ["Build", "test", "BUILD"]
counts = Counter(word.casefold() for word in words)
print(counts["build"])

06 Check your reasoning

QUICK SIGNAL CHECK

What does a frequency table store?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.