← Questions

Counter class with add, count and remove

0
MetaCodingLast asked Sep 2025

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 of s by one.
  • count(s: str) -> int — the current count of s, 0 if never added.
  • remove(s: str) -> bool — decreases the count of s by one, and forgets s when it reaches zero. Returns False if s was 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^5 operations. Each should take O(1) on average.

Clarifying questions

  • Does remove take 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 k distinct strings.
  • A running total kept on every add and remove, so total() 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

hash maps · design

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