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: Returns True when the collection contains zero elements, and False otherwise.
  • add(item) -> None: Inserts one occurrence of hashable item. Elements are grouped by value equality (==) rather than object identity (is).
  • count(item) -> int: Returns the current multiplicity of item (0 when item is not present).
  • remove(item) -> None: Deletes exactly one occurrence of item. Raises KeyError (without altering any counts) when item has multiplicity 0.
  • size() -> int: Returns the total number of stored occurrences summed across all distinct elements (0 when 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 Hashable values compared via == and hash().
  • add, count, remove, and is_empty should run in O(1) average time; size runs in O(D) (or O(1)) time for D distinct live elements, using O(D) space (zero-count entries must not accumulate in memory or break is_empty()).

Step-by-step walkthrough

  1. 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, and size() -> int. - Value equality vs. object identity: Two inputs represent the same element when a == b, even when a is not b. Using dictionary keys provides == matching in O(1) average time and requires elements to be hashable (having a stable hash() value across their lifetime, such as int, str, tuple, or a frozen dataclass, whereas mutable list or dict raises TypeError). - Missing-element removal: Raise KeyError (consistent with Python's built-in set.remove), leaving existing counts untouched. - Total size: size() sums multiplicities across all stored elements, so adding "bolt" twice and "washer" once yields size() == 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.
    
  2. 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 oracle
    
  3. Tests 1 and 2: `is_empty` and `add` with a boolean shortcut

    Begin with the zero-setup check: a freshly instantiated Multiset reports 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 True
    

    Next, Test 2 inserts one element ("bolt") and checks that is_empty() becomes False. Predict AttributeError because add does 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 = False
    

    Voice your reasoning explicitly: "Right now self._empty satisfies every test; as soon as we test count and duplicates, those tests will force us to track items and counts." That signals deliberate TDD discipline.

  4. Tests 3 and 4: `count` forces the upgrade to a dictionary

    Test 3 checks count on an empty instance, for the inserted element ("bolt"), and for an unseen element ("washer"). Checking "washer" blocks a fake return 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") == 0
    

    Storing a single self._item passes 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") == 1
    

    Look 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 list of copies against a dict of {item: count}: a dictionary gives O(1) average lookup time and uses one entry per distinct element rather than scanning every duplicate. Introduce self._counts: Dict[Hashable, int] = {} to go green, then refactor immediately by removing self._empty and returning len(self._counts) == 0 so 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)
    
  5. Test 5: `size` counts every copy

    Test 5 checks both 0 on a fresh instance and 3 after adding "bolt" twice and "washer" once, ruling out both return 0 and return len(self._counts) (which would return 2 distinct keys instead of 3 total 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() == 3
    

    Summing 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()) takes O(d) time across d distinct keys; maintaining a cached self._total counter would make size() O(1) at the price of updating two fields on every add and remove. Keep the single source of truth unless O(1) size() is requested.

  6. 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 proves remove decrements 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() == 3
    

    The 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!)      True
    

    Test 7 verifies that exact interaction between remove and is_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 1 to 0 establishes our class invariant (an internal property guaranteed before and after every call: self._counts never stores a zero count). Next, add Test 8 for removing an absent element (KeyError). Because self._counts[item] already raises KeyError, briefly stub if item not in self._counts: return to 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] -= 1
    
  7. Equality 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 often True). To verify value-based matching (==) rather than identity (is), Test 9 constructs two separate _Coord(3, 7) objects, asserts stored is not probe and stored == probe, inserts stored, and queries/removes via probe:

    @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) == 1
    

    Test 10 in tests.py cross-checks 200 randomized add/remove sequences 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 assert dict(bag.items()) == {"bolt": 2, "washer": 1}. - Iteration (__iter__): Add "washer", "bolt", "bolt" and assert sorted(bag) == ["bolt", "bolt", "washer"] so iteration order is not over-constrained. - Pythonic len(bag) and item in bag: Assert len(bag) == 3 (__len__) and "bolt" in bag (__contains__, O(1) via item in self._counts). - Static generics (Multiset[T]): Add Generic[T] with T = TypeVar("T", bound=Hashable) and check via mypy that Multiset[int]().add("wrong") fails static analysis. - Thread safety: Guard reads and writes with a threading.Lock, tested by 8 threads each calling bag.add("bolt") 10,000 times and asserting bag.count("bolt") == 80_000.

  8. 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, and is_empty: O(1) average time, because each operation performs one or two dictionary hash lookups/updates (get, key assignment, del, or checking len(self._counts)).
  • size: O(d) time, where d is the number of distinct elements currently stored, because sum(self._counts.values()) sums one integer per distinct key regardless of how many million copies each key has (caching a running _size integer would make size() 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 reaches 0 are deleted immediately.

Edge cases

  • Removing an absent element (from an empty or non-empty multiset): Raises KeyError without altering any existing counts.
  • Removing the final copy of the lone remaining element: Deletes the key from _counts rather than keeping 0, restoring is_empty() == True and allowing clean re-insertion later.
  • Equal but non-identical instances (first == second with first is not second): Matched as the same element because Python dictionaries compare keys by hash(x) followed by ==. Note that in Python 1 == 1.0 == True with identical hashes, so all three map to the same bucket.
  • Unhashable inputs (list, dict, set): Raise TypeError immediately on add or count; callers should convert mutable sequences into tuple or frozenset.
  • float("nan"): Because nan != nan under IEEE-754 floating-point rules, querying a newly created float("nan") object will not match a previously inserted nan unless 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 return True, Test 2 toggle a boolean, and Test 4 force the dictionary.
  • Leaving zero-count keys inside _counts: Decrementing {"bolt": 1} to {"bolt": 0} leaves len(self._counts) == 1, breaking is_empty() and leaking dead keys over long-lived workloads.
  • Testing remove when multiplicity is 1: With only a single copy present, del self._counts[item] ("delete every copy") and self._counts[item] -= 1 ("delete one copy") produce identical counts; test with 3 copies so a wipe-all bug fails with 0 != 2.
  • Testing == vs. is with string literals: Because CPython performs string interning (reusing one memory object for identical string literals), "bolt" is "bolt" is commonly True; construct separate equal instances (such as _Coord(3, 7) or tuple([3, 7])) and assert a is not b explicitly.
  • 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 KeyError on missing remove) 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) and class Multiset(Generic[T]):, and write Test 1 as Multiset[str]().is_empty(). Because Python uses type erasure (generic parameters like [str] are checked statically by tools such as mypy and stripped away at runtime), is_empty still begins as return True and Test 2 can still use a single boolean flag! The main shift is agreeing on the bound=Hashable constraint upfront before Test 1 and pairing runtime unit tests with a static type-checker check (verifying mypy rejects Multiset[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), call bag.remove("bolt") once, and assert bag.count("bolt") == 2, bag.count("washer") == 1, and bag.size() == 3. A single-copy setup cannot distinguish count -= 1 from del _counts[item] because both leave count 0, and checking "washer" in the same test ensures remove does 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 assert bag.most_common() == "bolt". This forces zero changes to self._counts: max(self._counts, key=self._counts.__getitem__) finds the winner in O(d) time across d distinct keys; an auxiliary heap or bucket index would only be needed if a later performance requirement demanded O(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

Similar questions

More Ode interview questions

All 2 Ode questions →