Data Structures · Visualization

Count-Min Sketch: Add

Count-Min Sketch

Adding touches exactly one counter per row — d increments total, no matter how many distinct items exist. Time: O(d) hashes per add. Space: O(1) extra.

Big-O: Add/estimate in O(d) hashes; tiny fixed memory.

Count-Min Sketch: Add

Count-Min Sketch

Adding touches exactly one counter per row — d increments total, no matter how many distinct items exist. That fixed cost is the whole point: a million-item stream costs the same per event as a ten-item one. Try your own words below and watch every row tick up together.

How Add Works

  1. Hash the item with each of the d hash functions.
  2. Increment those d counters by 1 (or by the event weight).
  3. Different items sharing a cell simply add up — collisions merge.
  4. No per-item bookkeeping is ever stored.

Add Worked Example

Input: Add 'berry' to a sketch holding apple×2, mango×1

  1. 'berry' hashes to (row0:4, row1:3).
  2. Bump row0/col4 → 1; row1/col3 was 2 (apple) → 3.
  3. Apple's row1 counter is now shared — its estimate may inflate.
  4. Mango untouched: its private cells stay exact.

Output: 2 counters bumped; total work O(d) = 2 hashes

Try your own input
Count-Min: Introduction
A tiny counter grid estimating frequencies — never underestimates.
row 0
0
0
0
0
0
0
0
0
row 1
0
0
0
0
0
0
0
0
row 2
0
0
0
0
0
0
0
0
Touched cell Non-zero counter
Count-Min: Introduction
Press ▶ Run to watch it step by step.
Python · Count-Min Sketch in Code
def add(sketch, x, w=1):
    for r in range(D):
        sketch[r][h(r, x)] += w   # one cell per row

grid = [[0] * W for _ in range(D)]  # tiny, fixed
# example: add
Input: Add 'berry' to a sketch holding apple×2, mango×1

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Add Time & Space Complexity

TimeO(d) hashes per add
SpaceO(1) extra

When to Use Add

  • Counting URL hits across a web fleet in fixed memory
  • Feature-frequency sketches feeding online ML models

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.