Thread-Safe Counter
Problem
Implement a Counter class that many threads increment concurrently. It must expose:
increment(n: int = 1) -> None: addnto the count.get() -> int: return the current count.increment_and_get(n: int = 1) -> int: addnand return the new value atomically, so that no two callers ever observe the same returned value if each adds 1.
Guarantees: no increment is ever lost, regardless of how threads interleave, and increment_and_get returns values that are unique and monotonically increasing across all threads when every caller adds 1. The class must not rely on the Python GIL for correctness; explain what would break under a runtime without it (or under a compound operation that the GIL does not make atomic).
Then implement a ShardedCounter that spreads increments across several internal counters to reduce contention, and reads by summing the shards.
incrementmust be safe to call from any number of threads.getmay return a slightly stale value for the sharded version but must never return a value that was not a real prefix of the increments.- No busy-waiting.
Examples
- 8 threads each call
increment()10,000 times →get()returns exactly 80,000. - 4 threads each call
increment_and_get()1,000 times → the 4,000 returned values are exactly the integers 1 through 4,000, each appearing once. ShardedCounter(shards=16)with the same 80,000 increments →get()returns 80,000 after all threads join.
Hints
count += 1is three operations, not one: read the current value, add, write it back. What happens if a second thread does the same three steps in between yours?- A mutual-exclusion lock around the whole read-modify-write makes the three steps indivisible from the point of view of other threads.
- Contention on one lock serializes every thread. If reads are rare and increments are hot, give each thread (or hash bucket) its own lock and sum on read.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.