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:
add_word(word: str) -> None: Stores one copy ofword. Repeated insertions of the exact same string are valid, and every stored copy contributes1toward its anagram group's size.remove_word(word: str) -> bool: Deletes a single stored copy of the exact stringwordand returnsTruewhen present. Ifworditself is not currently stored (even if other anagrams ofwordexist in the tracker), leave the collection unchanged and returnFalse.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
wordconsists strictly of lowercase English letters ('a'–'z'). 1 <= len(word) <= 100.- Total calls across
add_word,remove_word, andget_largest_groupwill not exceed100,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
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 ofword. Adding"tone","note", and"tone"builds an anagram group of size 3, not 2.remove_word(word): Removes one copy of the exact stringwordand returnsTrue, or returnsFalsewhenworditself is absent. Subtle trap: if the tracker holds"star", callingremove_word("arts")must returnFalseeven 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,000operations and words up to100lowercase letters, a workload can easily create tens of thousands of groups followed by tens of thousands ofget_largest_group()queries.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 lengthL):"".join(sorted("tone"))produces"enot", and so does"note". SinceL <= 100and Python'ssortedruns 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 linearO(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 Pythonsetloses duplicate copies ("tone"added twice would look like 1 word). - A Pythonlistkeeps duplicates, butlist.remove(word)scans the list inO(G)time for a group of sizeG. - A nested count dictionary{word: copy_count}(such as{"tone": 2, "note": 1}) preserves exact duplicate counts and supportsO(1)add and remove!- Sorted letters (
Compare the write-optimized baseline against the query constraint
If we only care about making
add_wordandremove_wordas lean as possible (write-optimized), we can store justgroups[group_key]plus an integersizes[group_key], and scansizeswheneverget_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_keyEvery write does minimal work, but each
get_largest_group()call scans allKactive groups inO(K + G)time (whereGis the size of the returned group). If a workload performs50,000add_wordcalls on distinct groups followed by50,000get_largest_groupcalls, scanning performs50,000 * 50,000 = 2.5 * 10^9loop iterations—far too slow for balanced or read-heavy workloads.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 groupsgroup_keys by their current integer size—the same frequency-bucket idea used inside an LFU (Least Frequently Used) cache—alongside a single integermax_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_sizenever requires a search loop onadd_wordorremove_word—every operation changes one group's size by at most 1:- On
add_word: One group moves fromold_sizetoold_size + 1. Ifold_size + 1 > max_size, thenmax_sizebecomesold_size + 1. - On
remove_word: One group moves fromold_sizedown toold_size - 1.- If
old_size < max_size, or if another group is still sitting inbuckets[max_size],max_sizedoes 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 inbuckets[max_size - 1](or reached0, meaning the entire tracker is now empty)! Because the shrinking group itself cushions the fall atmax_size - 1,max_sizealways drops toold_size - 1inO(1)time!
- If
- On
Code the bucket helper, add_word, and remove_word
A small helper
_move_between_buckets(group_key, old_size, new_size)keepsbucketsandsizessynchronized. Deletingself.buckets[old_size]as soon as its set becomes empty is critical: it ensuresold_size not in self.bucketsaccurately tells us when no group of sizeold_sizeremains.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 TrueCode get_largest_group in O(1) lookup + O(G) output
When
self.max_size == 0, the tracker is empty and we return[]. Otherwiseself.buckets[self.max_size]is guaranteed non-empty. Callingnext(iter(self.buckets[self.max_size]))peeks at one arbitrarygroup_keyfrom that set inO(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 resultReturning a newly built list also protects internal state: if the caller mutates or clears the returned list, our tracker's counts stay untouched.
Trace Example 1 step by step
Follow
groups,buckets, andmax_sizeacross 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 FalseLook closely at the two
remove("tone")lines: the first removal empties bucket3, somax_sizedrops from3to2; the second removal shrinks"enot"from2to1, yetmax_sizestays2because"arst"is still sitting inbuckets[2].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_wordandremove_word):O(L log L)average time—sorting theLcharacters buildsgroup_keyinO(L log L)(orO(L)if replaced by a 26-letter count tuple), followed by a constant number ofO(1)average-time dictionary and hash-set updates ingroups,sizes, andbuckets. - Time (
get_largest_group):O(G)average time—peeking atself.buckets[self.max_size]finds a winninggroup_keyinO(1)time, and expanding its counts into the output list touches each of theGreturned word instances once (which is optimal because constructing aG-element output list takes at leastGsteps). - Space:
O(D * L)memory—we store each of theDdistinct words once with an integer counter insidegroups, plus at mostKcanonical keys of length<= Lacrosssizesandbuckets(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_sizeis0,get_largest_group()returns[], andremove_word(...)returnsFalse. - Duplicate identical words: Calling
add_word("tone")twice incrementsgroups["enot"]["tone"]to2, contributing2to group size and appearing twice inget_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, returningFalsewithout 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], soold_size not in self.bucketsisFalseandmax_sizestays 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
setof strings: Loses duplicate copies of identical words, violating the rule that duplicate additions count toward group size. - Lowering
max_sizeunconditionally when a largest group shrinks: If two groups both have size3and one shrinks to2,max_sizemust remain3untilbuckets[3]is actually empty. - Forgetting to
del self.buckets[old_size]when a bucket becomes empty: Leaves empty sets lying around soold_size not in self.bucketsnever triggers andnext(iter(self.buckets[self.max_size]))crashes withStopIteration. - 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 aheapqheap on everyadd_wordandremove_wordinstead of maintainingbuckets. Lazy deletion means leaving outdated(size, key)entries inside the heap rather than searching for them, and only popping stale top entries duringget_largest_group()while-heap[0][0] != sizes.get(heap[0][1], 0). Writes takeO(L log L + log H)and reads take amortizedO(log H + G), though periodic heap compaction is needed if millions of updates accumulate stale heap entries. - Write-optimized map + dirty cache: Store only
groupsandsizes(nobuckets), plus acached_largest_keyinvalidated whenever a write can change the winner. Writes do fewer hash-table operations, while reads after writes payO(K + G)to rescansizes.
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 buildingtuple(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 accentU+0301and precomposed"é"U+00E9into 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 theregexpackage's\Xpattern) 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
Lcharacters ofword(Omega(L)lower bound) and every read must outputGwords (Omega(G)lower bound). Using a 26-integer frequency tuple key with our bucket tracker already achievesO(L)peradd_word/remove_wordandO(G)perget_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, droppingbucketsand scanningsizeson reads givesO(L)writes with roughly 3x fewer hash-table mutations per write andO(K + G)reads—and in a multi-threaded service, dropping globalbuckets/max_sizealso lets writers shard locks bygroup_keywithout contending on a single global maximum. - How would you synchronize the tracker when many threads read
get_largest_group()concurrently with threads callingadd_word()andremove_word()? Because a single add or remove mutatesgroups,sizes,buckets, andmax_sizetogether, an unsynchronized reader could observemax_size = 3right after a writer deletedbuckets[3]and crash withKeyError. Start with onethreading.Lockprotecting the shared dictionaries, keeping the critical section minimal: computeanagram_key(word)before acquiring the lock on writes, and insideget_largest_group()copy just the winning group'slist(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
- How would you redesign the group key when inputs may include general Unicode text rather than strictly `'a'`–`'z'`?
- 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?
- How would you synchronize the tracker when many threads read `get_largest_group()` concurrently with threads calling `add_word()` and `remove_word()`?
Similar questions
- Technical Deep Dive on a Defining Project
- Internal PKI and Mutual TLS Architecture
- Multi-Tenant Identity and Access Control Platform
- Scalable Resumable Video Upload and Processing Pipeline
- Minimum Flips to Join Two Islands
- Nearest Integer Value in a BST
More Coupang interview questions
- Minimum Flips to Join Two Islands Medium
- Signature Engineering Project: Impact, Lessons, and Hindsight Medium
- Technical Deep Dive on a Defining Project Medium Pro
- Internal PKI and Mutual TLS Architecture Medium Pro
- Multi-Tenant Identity and Access Control Platform Medium Pro
- Scalable Resumable Video Upload and Processing Pipeline Medium Pro
- Nearest Integer Value in a BST Easy Pro
- Monthly Cohort Retention Medium Pro
- Forecasting Next-Floor Elevator Demand Medium Pro
- Experiment Design for Dedicated Courier Elevators Medium Pro