← Questions
Counter class with add, count and remove
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Sep 2025. It tests hash maps and design.
Write a class that stores strings with the number of times each was added, and lets you look up and remove them.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
add(s: str) -> None— increases the count ofsby one. -
count(s: str) -> int— the current count ofs,0if never added. -
remove(s: str) -> bool— decreases the count ofsby one, and forgetsswhen it reaches zero. ReturnsFalseifswas not present.
Example
c = Counter()
c.add("apple")
c.add("apple")
c.add("pear")
c.count("apple") -> 2
c.remove("apple") -> True
c.count("apple") -> 1
c.remove("kiwi") -> False
c.total() -> 2 # follow-up: one apple, one pear
Constraints
- Up to
10^5operations. Each should take O(1) on average.
Clarifying questions
- Does
removetake away one occurrence or all of them? - What does removing a missing key do: return
False, raise, or ignore it? - Is the counter used by several threads at once?
- Are strings compared exactly, or case-insensitively?
What a strong answer covers
- A hash map from string to count, deleting entries that reach zero so memory follows the live keys.
- O(1) average time per operation and O(k) memory for
kdistinct strings. - A running total kept on every
addandremove, sototal()is O(1) instead of a sum over all keys. - Clean error behavior and tests for each method, including removing the last occurrence.
Follow-ups
- Return the total count across everything stored, in O(1).
- Make it generic: count any hashable type, and let the storage behind it be swapped (a hash map, a sorted map for ordered iteration).
- Make it safe for many threads. A single lock, lock striping, or per-thread counters merged on read: what does each cost?
- Return the most common item quickly after every operation.
Where it's asked
- Meta · AI-enabled coding · Last asked Sep 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
