Dynamic Anagram Multiset with Largest-Group Queries

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build an in-memory class AnagramGroupTracker (using only Python's standard library) that maintains a dynamic multiset of lowercase words partitioned into anagram groups. Two strings belong to the same anagram group when every character appears the exact same number of times in both strings (for instance, "star", "rats", and "arts").

Implement the following interface:

class AnagramGroupTracker:
    def __init__(self) -> None:
        pass

    def add_word(self, word: str) -> None:
        pass

    def remove_word(self, word: str) -> bool:
        pass

    def get_largest_group(self) -> List[str]:
        pass

Method behavior:

  1. add_word(word: str) -> None: Stores one copy of word. Repeated insertions of the exact same string are valid, and every stored copy contributes 1 toward its anagram group's size.
  2. remove_word(word: str) -> bool: Deletes a single stored copy of the exact string word and returns True when present. If word itself is not currently stored (even if other anagrams of word exist in the tracker), leave the collection unchanged and return False.
  3. get_largest_group() -> List[str]: Returns a list containing all stored word copies (duplicates included) from a single anagram group of maximum current size, in any order. When multiple groups share the largest size, returning any one complete tied group is valid. When no words are stored, return [].

Be ready to compare read-optimized and write-optimized designs so that get_largest_group() remains fast even when tens of thousands of groups and queries are interleaved.

Examples

Example 1

tracker = AnagramGroupTracker()
tracker.add_word("star")
tracker.add_word("rats")
tracker.add_word("tone")
tracker.get_largest_group()   # -> ["star", "rats"] (any order)

tracker.add_word("note")
tracker.add_word("stone")
tracker.add_word("tone")
tracker.get_largest_group()   # -> ["tone", "note", "tone"] (any order)

tracker.remove_word("tone")   # -> True
tracker.remove_word("tone")   # -> True
tracker.get_largest_group()   # -> ["star", "rats"] (any order)

tracker.remove_word("arts")   # -> False

Walk-through: Initially "star" and "rats" form a group of size 2, beating ["tone"] (size 1). Adding "note", "stone", and a second "tone" grows the "enot" group to size 3 (["tone", "note", "tone"]), which becomes the largest group. Removing both copies of "tone" shrinks that group back to ["note"] (size 1), so ["star", "rats"] (size 2) becomes largest again. Finally, remove_word("arts") returns False because "arts" itself was never inserted.

Example 2

tracker = AnagramGroupTracker()
tracker.get_largest_group()   # -> []

tracker.add_word("loop")
tracker.add_word("polo")
tracker.add_word("item")
tracker.add_word("time")
tracker.get_largest_group()   # -> ["loop", "polo"] or ["item", "time"] (any order)

tracker.remove_word("loop")   # -> True
tracker.get_largest_group()   # -> ["item", "time"] (any order)

Walk-through: On an empty tracker, get_largest_group() returns []. After inserting two pairs of anagrams, both groups tie at size 2, so either complete group is accepted. Removing "loop" drops its group to size 1, leaving ["item", "time"] as the sole largest group of size 2.

Constraints

  • Every word consists strictly of lowercase English letters ('a'–'z').
  • 1 <= len(word) <= 100.
  • Total calls across add_word, remove_word, and get_largest_group will not exceed 100,000.
  • Words inside the list returned by get_largest_group() may be ordered arbitrarily, and caller modifications to that returned list must not affect stored state.

Step-by-step walkthrough

  1. Restate the rules and spot the tricky cases

    Two words are anagrams when every character appears with the exact same count in both words (such as "star", "rats", and "arts"). Our tracker maintains a dynamic multiset of words—a collection where duplicate copies of the same string are allowed and every copy counts—across three operations:

    • add_word(word): Inserts one copy of word. Adding "tone", "note", and "tone" builds an anagram group of size 3, not 2.
    • remove_word(word): Removes one copy of the exact string word and returns True, or returns False when word itself is absent. Subtle trap: if the tracker holds "star", calling remove_word("arts") must return False even though "arts" maps to the same anagram group!
    • get_largest_group(): Returns a list of all word copies in one largest anagram group (in any order), or [] when empty. When two groups tie for largest, returning either complete group is valid—never a mix of both.

    With up to 100,000 operations and words up to 100 lowercase letters, a workload can easily create tens of thousands of groups followed by tens of thousands of get_largest_group() queries.

  2. Group anagrams with a canonical key and per-word counts

    To find any word's group in one dictionary lookup, compute a canonical key—a standardized representation that is identical for two words if and only if they are anagrams:

    • Sorted letters (O(L log L) for word length L): "".join(sorted("tone")) produces "enot", and so does "note". Since L <= 100 and Python's sorted runs in C, sorting <= 100 characters takes well under a microsecond and also works unchanged on general alphabets.
    • 26-letter frequency tuple (O(L)): Counting 'a'..'z' into a 26-integer tuple (0, ..., 1, ...) avoids sorting and runs in linear O(L) time.

    We use the clean sorted-letter key here:

    def anagram_key(word: str) -> str:
        """Return the canonical sorted-letter key shared by all anagrams of word (e.g. 'tone' -> 'enot')."""
        return "".join(sorted(word))
    

    Inside each group self.groups[group_key], how should we store the words? - A Python set loses duplicate copies ("tone" added twice would look like 1 word). - A Python list keeps duplicates, but list.remove(word) scans the list in O(G) time for a group of size G. - A nested count dictionary {word: copy_count} (such as {"tone": 2, "note": 1}) preserves exact duplicate counts and supports O(1) add and remove!

  3. Compare the write-optimized baseline against the query constraint

    If we only care about making add_word and remove_word as lean as possible (write-optimized), we can store just groups[group_key] plus an integer sizes[group_key], and scan sizes whenever get_largest_group() is called:

    class WriteOptimizedTracker:
        def __init__(self) -> None:
            self.groups = {}  # group_key -> {word: count}
            self.sizes = {}   # group_key -> total count in group
    
        def find_largest_key(self):
            best_key = None
            best_size = 0
            for group_key, group_size in self.sizes.items():
                if group_size > best_size:
                    best_key = group_key
                    best_size = group_size
            return best_key
    

    Every write does minimal work, but each get_largest_group() call scans all K active groups in O(K + G) time (where G is the size of the returned group). If a workload performs 50,000 add_word calls on distinct groups followed by 50,000 get_largest_group calls, scanning performs 50,000 * 50,000 = 2.5 * 10^9 loop iterations—far too slow for balanced or read-heavy workloads.

  4. Key idea: size buckets and the "step-by-one" maximum invariant

    How can we know the largest group in O(1) time even when words are removed from the largest group?

    Keep a second map buckets[size] that groups group_keys by their current integer size—the same frequency-bucket idea used inside an LFU (Least Frequently Used) cache—alongside a single integer max_size:

    buckets (only non-empty sizes exist)
      size 3: {"enot"}          <-- max_size = 3  (groups["enot"] = {"tone": 2, "note": 1})
      size 2: {"arst"}                            (groups["arst"] = {"star": 1, "rats": 1})
      size 1: {"enost"}                           (groups["enost"] = {"stone": 1})
    

    Notice why max_size never requires a search loop on add_word or remove_word—every operation changes one group's size by at most 1:

    1. On add_word: One group moves from old_size to old_size + 1. If old_size + 1 > max_size, then max_size becomes old_size + 1.
    2. On remove_word: One group moves from old_size down to old_size - 1.
      • If old_size < max_size, or if another group is still sitting in buckets[max_size], max_size does not change at all.
      • If this group was the last group in buckets[max_size], buckets[max_size] becomes empty and is deleted—and this very group just landed in buckets[max_size - 1] (or reached 0, meaning the entire tracker is now empty)! Because the shrinking group itself cushions the fall at max_size - 1, max_size always drops to old_size - 1 in O(1) time!
  5. Code the bucket helper, add_word, and remove_word

    A small helper _move_between_buckets(group_key, old_size, new_size) keeps buckets and sizes synchronized. Deleting self.buckets[old_size] as soon as its set becomes empty is critical: it ensures old_size not in self.buckets accurately tells us when no group of size old_size remains.

    from typing import Dict, List, Set
    
    
    class AnagramGroupTracker:
        def __init__(self) -> None:
            # groups: group_key -> {exact_word: copy_count}, e.g. {"arst": {"star": 2, "rats": 1}}
            self.groups: Dict[str, Dict[str, int]] = {}
            # sizes: group_key -> total word instances in that group, e.g. {"arst": 3}
            self.sizes: Dict[str, int] = {}
            # buckets: group_size -> non-empty set of group_keys at that size, e.g. {3: {"arst"}, 1: {"enot"}}
            self.buckets: Dict[int, Set[str]] = {}
            # max_size: size of the largest currently non-empty group (0 when tracker is empty)
            self.max_size: int = 0
    
        def _move_between_buckets(self, group_key: str, old_size: int, new_size: int) -> None:
            """Move group_key from buckets[old_size] to buckets[new_size], deleting empty buckets."""
            if old_size > 0:
                old_bucket = self.buckets[old_size]
                old_bucket.remove(group_key)
                if not old_bucket:
                    del self.buckets[old_size]
    
            if new_size > 0:
                if new_size not in self.buckets:
                    self.buckets[new_size] = set()
                self.buckets[new_size].add(group_key)
                self.sizes[group_key] = new_size
            else:
                del self.sizes[group_key]
    
        def add_word(self, word: str) -> None:
            """Insert one occurrence of word and advance its anagram group's size by 1."""
            group_key = anagram_key(word)
            if group_key not in self.groups:
                self.groups[group_key] = {}
            word_counts = self.groups[group_key]
            word_counts[word] = word_counts.get(word, 0) + 1
    
            old_size = self.sizes.get(group_key, 0)
            new_size = old_size + 1
            self._move_between_buckets(group_key, old_size, new_size)
            if new_size > self.max_size:
                self.max_size = new_size
    
        def remove_word(self, word: str) -> bool:
            """Remove one occurrence of exact word if present; return True if removed, False otherwise."""
            group_key = anagram_key(word)
            word_counts = self.groups.get(group_key)
            if word_counts is None or word not in word_counts:
                return False
    
            word_counts[word] -= 1
            if word_counts[word] == 0:
                del word_counts[word]
            if not word_counts:
                del self.groups[group_key]
    
            old_size = self.sizes[group_key]
            new_size = old_size - 1
            self._move_between_buckets(group_key, old_size, new_size)
    
            if old_size == self.max_size and old_size not in self.buckets:
                self.max_size = new_size
            return True
    
  6. Code get_largest_group in O(1) lookup + O(G) output

    When self.max_size == 0, the tracker is empty and we return []. Otherwise self.buckets[self.max_size] is guaranteed non-empty. Calling next(iter(self.buckets[self.max_size])) peeks at one arbitrary group_key from that set in O(1) time without removing it, and we expand each (word, word_count) pair into a brand-new list:

        def get_largest_group(self) -> List[str]:
            """Return a fresh list of all word instances in one largest anagram group, or [] when empty."""
            if self.max_size == 0:
                return []
    
            largest_key = next(iter(self.buckets[self.max_size]))
            result: List[str] = []
            for word, word_count in self.groups[largest_key].items():
                for _ in range(word_count):
                    result.append(word)
            return result
    

    Returning a newly built list also protects internal state: if the caller mutates or clears the returned list, our tracker's counts stay untouched.

  7. Trace Example 1 step by step

    Follow groups, buckets, and max_size across every operation in Example 1:

    Operation          groups                                       buckets                          max_size  Output
    ------------------------------------------------------------------------------------------------------------------------------
    add("star")        {"arst": {"star":1}}                         {1: {"arst"}}                    1         -
    add("rats")        {"arst": {"star":1,"rats":1}}                {2: {"arst"}}                    2         -
    add("tone")        {"arst": ..., "enot": {"tone":1}}            {2: {"arst"}, 1: {"enot"}}       2         -
    get_largest()      reads buckets[2] -> "arst"                   unchanged                        2         ["star","rats"]
    add("note")        "enot" -> {"tone":1,"note":1}                {2: {"arst","enot"}}             2         -
    add("stone")       "enost" -> {"stone":1}                       {2: {"arst","enot"}, 1:{"enost"}} 2        -
    add("tone")        "enot" -> {"tone":2,"note":1}                {3:{"enot"}, 2:{"arst"}, 1:...}  3         -
    get_largest()      reads buckets[3] -> "enot"                   unchanged                        3         ["tone","tone","note"]
    remove("tone")     "enot" 3->2; bucket 3 deleted!               {2:{"arst","enot"}, 1:{"enost"}} 2         True
    remove("tone")     "enot" 2->1; bucket 2 still has {"arst"}!    {2:{"arst"}, 1:{"enost","enot"}} 2         True
    get_largest()      reads buckets[2] -> "arst"                   unchanged                        2         ["star","rats"]
    remove("arts")     key "arst" has no exact "arts"               unchanged                        2         False
    

    Look closely at the two remove("tone") lines: the first removal empties bucket 3, so max_size drops from 3 to 2; the second removal shrinks "enot" from 2 to 1, yet max_size stays 2 because "arst" is still sitting in buckets[2].

  8. Complete solution

    from typing import Dict, List, Set
    
    
    def anagram_key(word: str) -> str:
        """Return the canonical sorted-letter key shared by all anagrams of word (e.g. 'tone' -> 'enot')."""
        return "".join(sorted(word))
    
    
    class AnagramGroupTracker:
        def __init__(self) -> None:
            # groups: group_key -> {exact_word: copy_count}, e.g. {"arst": {"star": 2, "rats": 1}}
            self.groups: Dict[str, Dict[str, int]] = {}
            # sizes: group_key -> total word instances in that group, e.g. {"arst": 3}
            self.sizes: Dict[str, int] = {}
            # buckets: group_size -> non-empty set of group_keys at that size, e.g. {3: {"arst"}, 1: {"enot"}}
            self.buckets: Dict[int, Set[str]] = {}
            # max_size: size of the largest currently non-empty group (0 when tracker is empty)
            self.max_size: int = 0
    
        def _move_between_buckets(self, group_key: str, old_size: int, new_size: int) -> None:
            """Move group_key from buckets[old_size] to buckets[new_size], deleting empty buckets."""
            # Phase A: Remove group_key from its previous size bucket (if it existed before).
            if old_size > 0:
                old_bucket = self.buckets[old_size]
                old_bucket.remove(group_key)
                # Delete empty buckets immediately so `size in self.buckets` means "at least one group has this size".
                if not old_bucket:
                    del self.buckets[old_size]
    
            # Phase B: Place group_key into its new size bucket (size 0 means the group is now empty).
            if new_size > 0:
                if new_size not in self.buckets:
                    self.buckets[new_size] = set()
                self.buckets[new_size].add(group_key)
                self.sizes[group_key] = new_size
            else:
                del self.sizes[group_key]
    
        def add_word(self, word: str) -> None:
            """Insert one occurrence of word and advance its anagram group's size by 1."""
            group_key = anagram_key(word)
            if group_key not in self.groups:
                self.groups[group_key] = {}
            word_counts = self.groups[group_key]
            word_counts[word] = word_counts.get(word, 0) + 1
    
            old_size = self.sizes.get(group_key, 0)
            new_size = old_size + 1
            self._move_between_buckets(group_key, old_size, new_size)
            if new_size > self.max_size:
                self.max_size = new_size
    
        def remove_word(self, word: str) -> bool:
            """Remove one occurrence of exact word if present; return True if removed, False otherwise."""
            group_key = anagram_key(word)
            word_counts = self.groups.get(group_key)
            # Check exact `word in word_counts`: an anagram like "arts" must not remove "star".
            if word_counts is None or word not in word_counts:
                return False
    
            word_counts[word] -= 1
            if word_counts[word] == 0:
                del word_counts[word]
            if not word_counts:
                del self.groups[group_key]
    
            old_size = self.sizes[group_key]
            new_size = old_size - 1
            self._move_between_buckets(group_key, old_size, new_size)
    
            # Why max_size drops by at most 1 without scanning: if this group was the sole occupant of
            # buckets[max_size], it just moved into buckets[old_size - 1] (or 0 when empty), cushioning the fall.
            if old_size == self.max_size and old_size not in self.buckets:
                self.max_size = new_size
            return True
    
        def get_largest_group(self) -> List[str]:
            """Return a fresh list of all word instances in one largest anagram group, or [] when empty."""
            if self.max_size == 0:
                return []
    
            # Pick any one group_key from the top non-empty bucket in O(1) time without removing it.
            largest_key = next(iter(self.buckets[self.max_size]))
            result: List[str] = []
            for word, word_count in self.groups[largest_key].items():
                for _ in range(word_count):
                    result.append(word)
            return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture organizing clubs onto numbered trophy shelves (Shelf 1, Shelf 2, Shelf 3, ...), where every word with the same sorted letters joins the same club ("star" and "rats" both map to club "arst"), and a pointer max_size tracks the highest occupied shelf. Whenever a word is added or removed, only one club changes membership, and its size changes by plus or minus 1. Even better, if the sole club sitting on the top shelf (Shelf 3) loses a word, that very club steps straight down onto Shelf 2—acting as a floor so max_size never drops by more than 1 and never requires scanning shelves to find the next largest group!

Why does the naive approach fall short? Keeping only a dictionary from sorted letters to a word list makes add_word easy, but forces get_largest_group() to scan every active group (O(K) across K groups, turning 50,000 groups x 50,000 queries into 2.5 billion checks) and forces remove_word() to linearly search a group's list (O(G)). Pairing a nested {word: count} map inside each group with buckets[size] eliminates both bottlenecks at once.

Walk through 4 calls from Example 1 to see every piece work together: 1. add_word("star") -> key "arst" gets {"star": 1}, enters buckets[1] = {"arst"}, and max_size becomes 1. 2. add_word("rats") -> key "arst" becomes {"star": 1, "rats": 1} (size 2), moves from buckets[1] (now deleted) to buckets[2] = {"arst"}, and max_size becomes 2. 3. add_word("tone") -> key "enot" gets {"tone": 1} in buckets[1] = {"enot"}; max_size stays 2, so get_largest_group() immediately looks up buckets[2], grabs "arst", and returns ["star", "rats"]. 4. remove_word("star") -> "arst" shrinks from 2 to 1, deleting empty buckets[2] and joining buckets[1] = {"enot", "arst"}; since 2 is no longer in buckets, max_size steps cleanly down to 2 - 1 = 1.

Complexity

Let L be the length of word (L <= 100), G be the total word instances in the returned largest group, D be the number of distinct words currently stored, and K be the number of active anagram groups (K <= D):

  • Time (add_word and remove_word): O(L log L) average time—sorting the L characters builds group_key in O(L log L) (or O(L) if replaced by a 26-letter count tuple), followed by a constant number of O(1) average-time dictionary and hash-set updates in groups, sizes, and buckets.
  • Time (get_largest_group): O(G) average time—peeking at self.buckets[self.max_size] finds a winning group_key in O(1) time, and expanding its counts into the output list touches each of the G returned word instances once (which is optimal because constructing a G-element output list takes at least G steps).
  • Space: O(D * L) memory—we store each of the D distinct words once with an integer counter inside groups, plus at most K canonical keys of length <= L across sizes and buckets (duplicate copies of an existing word only increment an integer and allocate no extra string entries).

Edge cases

  • Empty tracker (initially or after removing every word): max_size is 0, get_largest_group() returns [], and remove_word(...) returns False.
  • Duplicate identical words: Calling add_word("tone") twice increments groups["enot"]["tone"] to 2, contributing 2 to group size and appearing twice in get_largest_group().
  • Removing an anagram that was never added: If only "star" was added, remove_word("arts") hashes to "arst" but finds "arts" not in word_counts, returning False without shrinking "star".
  • Tied largest groups: buckets[max_size] holds multiple keys; next(iter(...)) returns all words of one complete tied group and never mixes words across groups.
  • Largest group shrinks while tied: Another key remains in buckets[max_size], so old_size not in self.buckets is False and max_size stays unchanged.
  • Same unique letters, different counts: "ab", "aab", and "abb" produce distinct sorted keys ("ab", "aab", "abb") and stay in separate groups.

Common mistakes

  • Using frozenset(word) as the anagram key: Sets discard character frequencies, falsely merging "aab" and "abb" into the same anagram group.
  • Storing each group as a set of strings: Loses duplicate copies of identical words, violating the rule that duplicate additions count toward group size.
  • Lowering max_size unconditionally when a largest group shrinks: If two groups both have size 3 and one shrinks to 2, max_size must remain 3 until buckets[3] is actually empty.
  • Forgetting to del self.buckets[old_size] when a bucket becomes empty: Leaves empty sets lying around so old_size not in self.buckets never triggers and next(iter(self.buckets[self.max_size])) crashes with StopIteration.
  • Returning an internal list directly from get_largest_group(): Lets caller mutations (such as .clear() or .append()) corrupt the tracker's internal state.

Alternative approaches

  • Max-heap with lazy deletion: Push (-new_size, group_key) onto a heapq heap on every add_word and remove_word instead of maintaining buckets. Lazy deletion means leaving outdated (size, key) entries inside the heap rather than searching for them, and only popping stale top entries during get_largest_group() while -heap[0][0] != sizes.get(heap[0][1], 0). Writes take O(L log L + log H) and reads take amortized O(log H + G), though periodic heap compaction is needed if millions of updates accumulate stale heap entries.
  • Write-optimized map + dirty cache: Store only groups and sizes (no buckets), plus a cached_largest_key invalidated whenever a write can change the winner. Writes do fewer hash-table operations, while reads after writes pay O(K + G) to rescan sizes.

Follow-up questions

  • How would you redesign the group key when inputs may include general Unicode text rather than strictly 'a'–'z'? A fixed 26-slot array no longer fits, whereas sorting characters ("".join(sorted(word))) or building tuple(sorted(Counter(word).items())) works across any alphabet—provided you normalize strings first with Unicode NFC normalization (unicodedata.normalize("NFC", word), which converts visually identical forms like "e" + combining accent U+0301 and precomposed "é" U+00E9 into the exact same code-point sequence). Decide explicitly whether matching is case-insensitive (word.casefold()). If multi-code-point emoji or accented scripts are allowed, split each word into grapheme clusters (user-perceived characters, such as via the regex package's \X pattern) before sorting so multi-code-point sequences like flag pairs or skin-tone modifiers stay intact instead of having their raw code points scrambled across characters.
  • Under an overwhelmingly write-dominant workload (for instance, 99% updates and 1% queries), what per-operation time bounds are optimal and how would you simplify the structure? Every correct write must inspect all L characters of word (Omega(L) lower bound) and every read must output G words (Omega(G) lower bound). Using a 26-integer frequency tuple key with our bucket tracker already achieves O(L) per add_word / remove_word and O(G) per get_largest_group(), which is asymptotically optimal for both! However, if reads are truly rare (say, 0.01% of traffic) and memory or write latency is tight, dropping buckets and scanning sizes on reads gives O(L) writes with roughly 3x fewer hash-table mutations per write and O(K + G) reads—and in a multi-threaded service, dropping global buckets/max_size also lets writers shard locks by group_key without contending on a single global maximum.
  • How would you synchronize the tracker when many threads read get_largest_group() concurrently with threads calling add_word() and remove_word()? Because a single add or remove mutates groups, sizes, buckets, and max_size together, an unsynchronized reader could observe max_size = 3 right after a writer deleted buckets[3] and crash with KeyError. Start with one threading.Lock protecting the shared dictionaries, keeping the critical section minimal: compute anagram_key(word) before acquiring the lock on writes, and inside get_largest_group() copy just the winning group's list(self.groups[largest_key].items()) under the lock before expanding strings outside the lock. If read concurrency is very high and writes are infrequent, replace the single mutex with a readers-writer lock (allowing many simultaneous readers when no writer holds the lock) or publish an atomic reference to an immutable copy-on-write snapshot of the current largest group.

Follow-up questions

Similar questions

More Coupang interview questions

All 11 Coupang questions →