Building a Multiset Incrementally with TDD
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
In this collaborative test-driven development (TDD) exercise, you act as the navigator guiding an interviewer at the keyboard to build a Multiset container — an unordered collection where equal elements can be inserted multiple times and each element's multiplicity is tracked.
Rather than writing the full data structure upfront, grow Multiset incrementally through strict Red-Green-Refactor cycles: propose one small behavioral test, watch it fail for the expected reason, and introduce only the minimal code change required to pass all active tests (for instance, returning a constant or toggling a boolean before any test checks per-item multiplicities, then refactoring to a counting map once duplicate and multi-element tests force it). Cover the entire public API breadth-first before deep-diving into edge cases, and keep a prioritized test-first backlog of future enhancements (such as iteration, distinct element-count views, generic type annotations, or thread safety).
Implement Multiset with the following contract:
Multiset(): Constructs an empty multiset.is_empty() -> bool: ReturnsTruewhen the collection contains zero elements, andFalseotherwise.add(item) -> None: Inserts one occurrence of hashableitem. Elements are grouped by value equality (==) rather than object identity (is).count(item) -> int: Returns the current multiplicity ofitem(0whenitemis not present).remove(item) -> None: Deletes exactly one occurrence ofitem. RaisesKeyError(without altering any counts) whenitemhas multiplicity0.size() -> int: Returns the total number of stored occurrences summed across all distinct elements (0when empty).
Examples
Example 1
bag = Multiset()
bag.is_empty() # -> True
bag.size() # -> 0
bag.add("bolt")
bag.add("bolt")
bag.add("washer")
bag.is_empty() # -> False
bag.count("bolt") # -> 2
bag.count("washer") # -> 1
bag.count("nut") # -> 0
bag.size() # -> 3
bag.remove("bolt")
bag.count("bolt") # -> 1
bag.size() # -> 2
Walk-through: Inserting "bolt" twice and "washer" once yields multiplicity 2 for "bolt", 1 for "washer", 0 for unseen "nut", and total size() of 3. Calling remove("bolt") decrements "bolt" from 2 to 1 while leaving "washer" untouched.
Example 2
bag = Multiset()
# bag.remove("bolt") -> raises KeyError on an empty multiset
first = (3, 7)
second = tuple([3, 7]) # first == second, first is not second
bag.add(first)
bag.count(second) # -> 1 (matched by == equality)
bag.remove(second)
bag.count(first) # -> 0
bag.size() # -> 0
bag.is_empty() # -> True
Walk-through: Removing a missing key raises KeyError. Distinct tuple instances with equal contents map to the same entry, and removing the final copy restores count == 0, size() == 0, and is_empty() == True.
Constraints
- Stored items are Python
Hashablevalues compared via==andhash(). add,count,remove, andis_emptyshould run inO(1)average time;sizeruns inO(D)(orO(1)) time forDdistinct live elements, usingO(D)space (zero-count entries must not accumulate in memory or breakis_empty()).
Step-by-step walkthrough
Agree on the behavior contract and the TDD loop
A multiset (also called a bag) is an unordered container that permits repeated values and records each value's multiplicity. In a collaborative Test-Driven Development (TDD) pairing session — an incremental workflow where every line of production logic is justified by a preceding failing test — you guide the session aloud one small behavior at a time.
Clarify every contract detail before dictating Test 1 so each rule maps cleanly to a test: - Core API:
is_empty() -> bool,add(item) -> None,count(item) -> int,remove(item) -> None, andsize() -> int. - Value equality vs. object identity: Two inputs represent the same element whena == b, even whena is not b. Using dictionary keys provides==matching inO(1)average time and requires elements to be hashable (having a stablehash()value across their lifetime, such asint,str,tuple, or a frozen dataclass, whereas mutablelistordictraisesTypeError). - Missing-element removal: RaiseKeyError(consistent with Python's built-inset.remove), leaving existing counts untouched. - Total size:size()sums multiplicities across all stored elements, so adding"bolt"twice and"washer"once yieldssize() == 3.Follow the Red-Green-Refactor discipline strictly at every step:
1. RED Dictate one focused test, predict the exact failure (AttributeError or AssertionError), and run it. 2. GREEN Dictate the smallest code change that makes all active tests pass — zero speculative extras! 3. REFACTOR Once every test is green, eliminate redundant state or shortcuts, and re-run the suite.Map out a breadth-first test progression
Because pairing sessions have tight timeboxes, sweep across all five methods breadth-first before tackling subtler corner cases. Sequence your tests so each new test invalidates the previous shortcut for one unmistakable reason:
# Test name Predicted failure -> Minimal change forced 1 test_new_multiset_is_empty NameError/AttributeError -> is_empty() returns True 2 test_not_empty_after_add AttributeError -> add() flips one boolean _empty 3 test_count_is_one_for_the_added_item_and_zero_for_others AttributeError -> store one _item field 4 test_count_after_adding_twice_is_two AssertionError (0 == 2) -> replace _item/_empty with _counts dict 5 test_size_counts_every_copy AttributeError -> size() sums _counts.values() 6 test_remove_takes_away_exactly_one_copy AttributeError -> remove() decrements _counts[item] 7 test_removing_last_copy_empties_the_multiset AssertionError -> delete key when count hits 0 8 test_remove_absent_item_raises_and_changes_nothing Passes immediately -> mutate code briefly to prove test fails 9 test_items_match_by_equality_not_identity Passes immediately -> pins == vs is with distinct objects 10 test_random_operations_match_a_list_model Cross-checks sequences against a simple list oracleTests 1 and 2: `is_empty` and `add` with a boolean shortcut
Begin with the zero-setup check: a freshly instantiated
Multisetreports empty.def test_new_multiset_is_empty(): """A newly constructed multiset starts empty.""" assert Multiset().is_empty()After watching it fail, dictate the minimal passing implementation — no dictionary yet!
class Multiset: def is_empty(self) -> bool: return TrueNext, Test 2 inserts one element (
"bolt") and checks thatis_empty()becomesFalse. PredictAttributeErrorbecauseadddoes not exist yet:def test_not_empty_after_add(): """After one add the multiset is no longer empty.""" bag = Multiset() bag.add("bolt") assert not bag.is_empty()Still avoid introducing a map or list! No test has asked which item was inserted or how many copies exist. A single boolean attribute satisfies both tests cleanly:
class Multiset: def __init__(self) -> None: self._empty = True def is_empty(self) -> bool: return self._empty def add(self, item: Hashable) -> None: self._empty = FalseVoice your reasoning explicitly: "Right now
self._emptysatisfies every test; as soon as we testcountand duplicates, those tests will force us to track items and counts." That signals deliberate TDD discipline.Tests 3 and 4: `count` forces the upgrade to a dictionary
Test 3 checks
counton an empty instance, for the inserted element ("bolt"), and for an unseen element ("washer"). Checking"washer"blocks a fakereturn 0 if self._empty else 1:def test_count_is_one_for_the_added_item_and_zero_for_others(): """count is 0 before any add, 1 for the item added once, and 0 for an item never added.""" bag = Multiset() assert bag.count("bolt") == 0 bag.add("bolt") assert bag.count("bolt") == 1 assert bag.count("washer") == 0Storing a single
self._itempasses Test 3. Now Test 4 adds"bolt"twice and"washer"once, finally forcing multi-item multiplicity storage:def test_count_after_adding_twice_is_two(): """Adding the same item twice counts it twice; a different item keeps its own count.""" bag = Multiset() bag.add("bolt") bag.add("bolt") bag.add("washer") assert bag.count("bolt") == 2 assert bag.count("washer") == 1Look at why the single-item field breaks on Test 4:
Call Single-field shortcut (_item) Counting dict (_counts) add("bolt") _item = "bolt" {"bolt": 1} add("bolt") _item = "bolt" (lost 2nd copy!) {"bolt": 2} add("washer") _item = "washer" (lost "bolt"!) {"bolt": 2, "washer": 1} count("bolt") returns 0 != 2 (FAIL) returns 2 (PASS)Briefly contrast a
listof copies against adictof{item: count}: a dictionary givesO(1)average lookup time and uses one entry per distinct element rather than scanning every duplicate. Introduceself._counts: Dict[Hashable, int] = {}to go green, then refactor immediately by removingself._emptyand returninglen(self._counts) == 0so emptiness has a single source of truth:class Multiset: def __init__(self) -> None: self._counts: Dict[Hashable, int] = {} def is_empty(self) -> bool: return len(self._counts) == 0 def add(self, item: Hashable) -> None: current_count = self._counts.get(item, 0) self._counts[item] = current_count + 1 def count(self, item: Hashable) -> int: return self._counts.get(item, 0)Test 5: `size` counts every copy
Test 5 checks both
0on a fresh instance and3after adding"bolt"twice and"washer"once, ruling out bothreturn 0andreturn len(self._counts)(which would return2distinct keys instead of3total occurrences):def test_size_counts_every_copy(): """size is 0 when new and counts duplicates: bolt, bolt, washer gives 3.""" bag = Multiset() assert bag.size() == 0 bag.add("bolt") bag.add("bolt") bag.add("washer") assert bag.size() == 3Summing the dictionary's values makes Test 5 pass in one line:
def size(self) -> int: # Sum all copy counts across distinct keys (len(self._counts) would only count distinct items). return sum(self._counts.values())Note the complexity trade-off aloud:
sum(self._counts.values())takesO(d)time acrossddistinct keys; maintaining a cachedself._totalcounter would makesize()O(1)at the price of updating two fields on everyaddandremove. Keep the single source of truth unlessO(1)size()is requested.Tests 6, 7, and 8: `remove` and the no-zero-counts invariant
In Test 6, insert three copies of
"bolt"alongside"washer"so the test provesremovedecrements by one rather than deleting the entire key:def test_remove_takes_away_exactly_one_copy(): """With bolt x3 and washer x1, removing bolt once leaves bolt x2, washer x1, size 3.""" bag = Multiset() for item in ["bolt", "bolt", "washer", "bolt"]: bag.add(item) bag.remove("bolt") assert bag.count("bolt") == 2 assert bag.count("washer") == 1 assert bag.size() == 3The minimal change for Test 6 is
self._counts[item] -= 1. Follow it immediately with Test 7 to expose the leftover-zero bug:Action Decrement-only _counts len(_counts) == 0 Desired is_empty() bag.add("bolt") {"bolt": 1} False False bag.remove("bolt") {"bolt": 0} <-- trap! False (WRONG!) TrueTest 7 verifies that exact interaction between
removeandis_empty:def test_removing_last_copy_empties_the_multiset(): """add then remove the only item: count 0, size 0, empty again, and the item can be added back.""" bag = Multiset() bag.add("bolt") bag.remove("bolt") assert bag.count("bolt") == 0 assert bag.size() == 0 assert bag.is_empty() bag.add("bolt") assert bag.count("bolt") == 1 assert not bag.is_empty()Deleting the dictionary key whenever its count drops from
1to0establishes our class invariant (an internal property guaranteed before and after every call:self._countsnever stores a zero count). Next, add Test 8 for removing an absent element (KeyError). Becauseself._counts[item]already raisesKeyError, briefly stubif item not in self._counts: returnto confirm Test 8 fails as expected, then restore the explicit check:def remove(self, item: Hashable) -> None: if item not in self._counts: raise KeyError(item) # Delete the key when removing its last copy so _counts never holds 0 (keeps is_empty() valid). if self._counts[item] == 1: del self._counts[item] else: self._counts[item] -= 1Equality vs. identity, model checking, and the follow-on backlog
In CPython, identical string literals often share the same object address via string interning (
"bolt" is "bolt"is oftenTrue). To verify value-based matching (==) rather than identity (is), Test 9 constructs two separate_Coord(3, 7)objects, assertsstored is not probe and stored == probe, insertsstored, and queries/removes viaprobe:@dataclass(frozen=True) class _Coord: """A hashable value type: two _Coord(3, 7) objects are equal but not identical.""" x: int y: int def test_items_match_by_equality_not_identity(): """An equal but distinct object counts as the same item, for count and for remove.""" stored = _Coord(3, 7) probe = _Coord(3, 7) assert stored is not probe and stored == probe bag = Multiset() bag.add(stored) bag.add(stored) assert bag.count(probe) == 2 bag.remove(probe) assert bag.count(stored) == 1Test 10 in
tests.pycross-checks200randomizedadd/removesequences against a plain list-backed oracle. Finally, wrap up the session by naming your prioritized backlog items along with the first failing test for each: - Distinct element-count pairs (items()): Add"bolt", "bolt", "washer"and assertdict(bag.items()) == {"bolt": 2, "washer": 1}. - Iteration (__iter__): Add"washer", "bolt", "bolt"and assertsorted(bag) == ["bolt", "bolt", "washer"]so iteration order is not over-constrained. - Pythoniclen(bag)anditem in bag: Assertlen(bag) == 3(__len__) and"bolt" in bag(__contains__,O(1)viaitem in self._counts). - Static generics (Multiset[T]): AddGeneric[T]withT = TypeVar("T", bound=Hashable)and check viamypythatMultiset[int]().add("wrong")fails static analysis. - Thread safety: Guard reads and writes with athreading.Lock, tested by8threads each callingbag.add("bolt")10,000times and assertingbag.count("bolt") == 80_000.Complete solution
from typing import Dict, Hashable class Multiset: """A bag: holds items, each possibly several times, and remembers how many times. Policies agreed with the interviewer before the first test: - two items are the same when they are equal (==), as dict keys are; items must be hashable - remove(item) takes away one copy and raises KeyError if the item is not present """ def __init__(self) -> None: # _counts: dict mapping each distinct item -> positive copy count, e.g. {"bolt": 2, "washer": 1}. # Invariant: every stored count is >= 1; zero-count keys are deleted immediately. self._counts: Dict[Hashable, int] = {} def is_empty(self) -> bool: # Because zero-count keys are never kept, an empty dict guarantees zero items in O(1) time. return len(self._counts) == 0 def add(self, item: Hashable) -> None: current_count = self._counts.get(item, 0) self._counts[item] = current_count + 1 def count(self, item: Hashable) -> int: return self._counts.get(item, 0) def remove(self, item: Hashable) -> None: if item not in self._counts: raise KeyError(item) # Delete the key when removing its last copy so _counts never holds 0 (keeps is_empty() valid). if self._counts[item] == 1: del self._counts[item] else: self._counts[item] -= 1 def size(self) -> int: # Sum all copy counts across distinct keys (len(self._counts) would only count distinct items). return sum(self._counts.values())✅ Submit now — all tests should pass.
Intuition & how it works
Picture a multiset (an unordered bag that permits duplicate items and tracks each item's multiplicity) like a hardware-bin inventory sheet: instead of writing "bolt" on ten separate lines, the sheet keeps one row per distinct part with a quantity beside it ("bolt": 2, "washer": 1). In a Test-Driven Development (TDD) pairing session — where you introduce one failing test at a time and write only the minimal code required to turn that test green — you act like a rally co-driver calling out one turn at a time rather than paving the entire course upfront.
Two naive approaches fall short here. Coding the full dictionary structure on Test 1 breaks test-first discipline because no failing test required item storage yet. On the data-structure side, appending every duplicate to a flat list (["bolt", "bolt", "washer"]) forces count and remove to scan up to n elements in O(n) time, while decrementing a dictionary entry to 0 without deleting its key leaves {"bolt": 0} behind after remove("bolt"), making is_empty() return False on an empty bag.
Our final implementation uses a hash table (dict, a key-value store that locates entries in O(1) average time via their hash code) mapping each hashable element (an immutable-value object with consistent hash() and == semantics) to its positive multiplicity, enforcing a strict class invariant (an internal rule guaranteed before and after every method call: zero-count keys are deleted immediately).
Walk through Example 1 and final-copy removal on bag = Multiset() to see how _counts evolves:
1. bag = Multiset() -> _counts = {}, is_empty() == True, size() == 0.
2. bag.add("bolt") -> _counts = {"bolt": 1}, is_empty() == False, count("bolt") == 1.
3. bag.add("bolt") and bag.add("washer") -> _counts = {"bolt": 2, "washer": 1}, count("nut") == 0, size() == 3.
4. bag.remove("bolt") -> multiplicity drops from 2 to 1: _counts = {"bolt": 1, "washer": 1}, count("bolt") == 1, size() == 2.
5. Removing "bolt" once more sees multiplicity 1 and deletes the key completely (_counts = {"washer": 1}); removing "washer" next leaves _counts = {} and is_empty() == True.
Complexity
add,count,remove, andis_empty:O(1)average time, because each operation performs one or two dictionary hash lookups/updates (get, key assignment,del, or checkinglen(self._counts)).size:O(d)time, wheredis the number of distinct elements currently stored, becausesum(self._counts.values())sums one integer per distinct key regardless of how many million copies each key has (caching a running_sizeinteger would makesize()O(1)if high-frequency size lookups were needed).- Space:
O(d)memory, storing at most one dictionary entry per distinct live item because keys whose multiplicity reaches0are deleted immediately.
Edge cases
- Removing an absent element (from an empty or non-empty multiset): Raises
KeyErrorwithout altering any existing counts. - Removing the final copy of the lone remaining element: Deletes the key from
_countsrather than keeping0, restoringis_empty() == Trueand allowing clean re-insertion later. - Equal but non-identical instances (
first == secondwithfirst is not second): Matched as the same element because Python dictionaries compare keys byhash(x)followed by==. Note that in Python1 == 1.0 == Truewith identical hashes, so all three map to the same bucket. - Unhashable inputs (
list,dict,set): RaiseTypeErrorimmediately onaddorcount; callers should convert mutable sequences intotupleorfrozenset. float("nan"): Becausenan != nanunder IEEE-754 floating-point rules, querying a newly createdfloat("nan")object will not match a previously insertednanunless it is the exact same object reference.
Common mistakes
- Building
self._counts = {}immediately on Test 1: Writing storage machinery before any failing test requires it undermines the core goal of incremental TDD pairing; let Test 1 returnTrue, Test 2 toggle a boolean, and Test 4 force the dictionary. - Leaving zero-count keys inside
_counts: Decrementing{"bolt": 1}to{"bolt": 0}leaveslen(self._counts) == 1, breakingis_empty()and leaking dead keys over long-lived workloads. - Testing
removewhen multiplicity is1: With only a single copy present,del self._counts[item]("delete every copy") andself._counts[item] -= 1("delete one copy") produce identical counts; test with3copies so a wipe-all bug fails with0 != 2. - Testing
==vs.iswith string literals: Because CPython performs string interning (reusing one memory object for identical string literals),"bolt" is "bolt"is commonlyTrue; construct separate equal instances (such as_Coord(3, 7)ortuple([3, 7])) and asserta is not bexplicitly. - Asserting on private attributes (
assert bag._counts == ...): Locks tests to internal representation details and breaks tests unnecessarily during refactoring. - Accepting a newly written test that passes immediately: When a new test (like
KeyErroron missingremove) goes green on the first run, briefly break the code for a moment to confirm the test actually catches a regression.
Follow-up questions
- How would your initial test and minimal code change if static generic typing (Multiset[T]) were required right from step one? In Python, you would declare
T = TypeVar("T", bound=Hashable)andclass Multiset(Generic[T]):, and write Test 1 asMultiset[str]().is_empty(). Because Python uses type erasure (generic parameters like[str]are checked statically by tools such asmypyand stripped away at runtime),is_emptystill begins asreturn Trueand Test 2 can still use a single boolean flag! The main shift is agreeing on thebound=Hashableconstraint upfront before Test 1 and pairing runtime unit tests with a static type-checker check (verifyingmypyrejectsMultiset[int]().add("bolt")). - What minimal test case proves that remove deletes just a single copy of a repeated element rather than wiping out every copy? Insert the same element at least twice (for example
"bolt"three times alongside"washer"once), callbag.remove("bolt")once, and assertbag.count("bolt") == 2,bag.count("washer") == 1, andbag.size() == 3. A single-copy setup cannot distinguishcount -= 1fromdel _counts[item]because both leave count0, and checking"washer"in the same test ensuresremovedoes not clobber unrelated keys. - If asked to add a method returning the highest-frequency element, what first test would you write, and would you need to alter the underlying dictionary? First clarify two boundary behaviors: what happens on an empty multiset (e.g., raise
ValueError) and how ties are resolved (any tied element vs. earliest inserted). Then dictate the simplest happy-path test: insert"washer","bolt","bolt"and assertbag.most_common() == "bolt". This forces zero changes toself._counts:max(self._counts, key=self._counts.__getitem__)finds the winner inO(d)time acrossddistinct keys; an auxiliary heap or bucket index would only be needed if a later performance requirement demandedO(1)queries under heavy updates. - What criterion distinguishes a minimal implementation that merely needs refactoring from a shortcut that is still missing a behavioral test? Ask whether any valid sequence of public method calls under the agreed contract can make the current implementation return the wrong result. If such a call sequence exists, the code is behaviorally incomplete, and that exact call sequence is your next failing test (for instance,
add("bolt")->remove("bolt")->is_empty()exposes a stale boolean flag). If no public call sequence can make it misbehave, the observable behavior is complete, and cleaning up internal duplication belongs in the Refactor step while the suite stays green.
Follow-up questions
- How would your initial test and minimal code change if static generic typing (Multiset[T]) were required right from step one?
- What minimal test case proves that remove deletes just a single copy of a repeated element rather than wiping out every copy?
- If asked to add a method returning the highest-frequency element, what first test would you write, and would you need to alter the underlying dictionary?
- What criterion distinguishes a minimal implementation that merely needs refactoring from a shortcut that is still missing a behavioral test?
Similar questions
- Incremental TDD Pair Session: Building a Java Set
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager