Exact String Lookup with Uniform Random Sampling
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement a read-only in-memory class StringCollection that ingests an iterable of strings once at construction time and supports fast exact-match queries alongside fair random draws:
__init__(self, strings: Iterable[str], rng: Optional[random.Random] = None) -> None: Consumestrings(which may be a list, set, or single-pass generator), deduplicate repeated values so each distinct string is kept once, and raiseValueErrorimmediately if no strings were supplied. Subsequent changes to the caller's input container must not affect the collection. Whenrngis provided, use it for all random draws; otherwise create an independentrandom.Randominstance.contains(self, value: str) -> bool: ReturnTruewhenvaluematches a stored string character-for-character, andFalseotherwise. Matching is strictly exact—substrings, prefixes, altered letter case, or leading/trailing whitespace do not match unless that exact string was stored.get_random(self) -> str: Return one stored string such that every distinct stored string has probability1 / nof being selected, regardless of how many duplicate copies appeared instrings.__len__(self) -> int: Returnn, the number of distinct strings stored.
Design your internal storage so neither contains nor get_random degrades to a linear scan over n items, keep character and index memory overhead low when n is large, and consider how your layout compares against a trie (prefix tree) when prefix queries are not needed.
Examples
Example 1
Input:
store = StringCollection(["tcp", "http", "tls", "http"])
len(store)
store.contains("tls")
store.contains("ht")
store.contains("HTTP")
store.get_random()
Output:
len(store) -> 3
store.contains("tls") -> True
store.contains("ht") -> False
store.contains("HTTP") -> False
store.get_random() -> "tcp", "http", or "tls" (each with probability 1/3)
Walk-through: The second "http" is discarded during initialization, leaving three distinct protocol names ("tcp", "http", "tls"). "tls" matches stored text exactly, whereas "ht" is only a prefix and "HTTP" differs in casing. Because duplicates are collapsed before sampling, "http" has the same 1/3 draw probability as "tcp" and "tls" rather than 2/4.
Example 2
Input:
store = StringCollection([""])
len(store)
store.contains("")
store.contains(" ")
store.get_random()
Output:
len(store) -> 1
store.contains("") -> True
store.contains(" ") -> False
store.get_random() -> ""
Walk-through: An empty string "" is still a valid string value, so the collection has size 1, matches "" exactly, rejects a single space " ", and always draws "".
Example 3
Input:
StringCollection([])
Output:
Raises ValueError
Walk-through: An empty input has zero elements, making uniform selection undefined, so __init__ rejects it immediately with ValueError.
Constraints
- At least
1string must be yielded bystrings; empty iterables ([],set(), exhausted generators) must raiseValueError. - Individual strings may have length
0("") or arbitrary ASCII/Unicode text, and the collection may hold up to10^6distinct strings where both string payload and index memory matter. contains(value)must run inO(L)expected time for a query string of lengthL, andget_random()must run inO(1)time per draw.- No insertions or removals occur after
__init__completes.
Step-by-step walkthrough
Restate the problem and settle the design rules
We need an in-memory string collection built once from an input sequence of strings. After initialization, nothing is added or removed, and the collection must answer two queries quickly:
contains(value) -> bool: returnTrueifvalueis an exact match for a stored string, andFalseotherwise.get_random() -> str: return one stored string so that every stored string has the exact same1 / nchance of being picked, wherenis the number of distinct stored strings.
In an interview, start by pinning down the edge cases and API invariants:
- Duplicates in the input are deduplicated. Each distinct value is stored once, so uniform sampling means uniform over distinct strings. Passing
["tcp", "http", "tls", "http"]stores three strings ("tcp","http", and"tls"), each sampled with probability1/3. - Immutable after construction. Mutating the caller's input list later must not alter our collection, and generators (single-pass iterators) should work too.
- At least one string is required. Raising
ValueErrorin__init__when no strings are given fails fast instead of crashing later insideget_random(). - Reproducible randomness. Accepting an optional
random.Randominstance lets unit tests pass a fixed seed without touching Python's globalrandommodule.
Why a single data structure falls short
Notice that our two operations ask for two completely different ways of finding data:
- Array / list only: Every string sits at an integer index
0 .. n - 1, soget_random()just picks a random index inO(1)time. However,contains(value)has to comparevalueagainst up to allnstrings one by one, takingO(n * L)time in the worst case for strings of lengthL. - Hash set only: A hash set computes an integer fingerprint (a hash) from the string's characters to jump straight to a bucket, making
contains(value)O(L)expected time. However, a hash set leaves empty slots scattered across its internal table and provides no way to jump to the "k-th stored string" inO(1)time.
Converting the set to a list on every sample defeats the purpose:
import random def slow_get_random(strings_set): # Copying n elements on every call turns a fast sample into O(n) work return random.choice(list(strings_set))With
n = 1,000,000strings and100,000calls toget_random(), copying the set on each call visits10^11slots. We need both operations to be fast at the same time.- Array / list only: Every string sits at an integer index
Key idea: pair a hash set with a positional tuple
Instead of forcing one container to do both jobs, we keep two views of the exact same string objects:
self._index(aset) maps each string's content to its hash bucket socontains(value)runs inO(L)expected time.self._items(atuple) assigns each distinct string a dense integer index0, 1, ..., n - 1soget_random()picks one random integer and indexes inO(1)time.
In Python, containers store 8-byte object references (memory addresses) rather than copying the string's characters. Both structures point to the same underlying
strobjects in memory:_items (tuple: dense positions for O(1) random index) +-----+-----+-----+ | 0 | 1 | 2 | +--+--+--+--+--+--+ | | | v v v "tcp" "http" "tls" <-- character data stored ONCE in memory ^ ^ ^ | | | +--+--+--+--+--+--+-----+-----+ | . | | . | | . | +-----+-----+-----+-----+-----+ _index (hash set: sparse buckets for O(L) exact lookup)Let's check the concrete memory footprint on 64-bit CPython 3.13 (measured with
sys.getsizeof) for1,000,000distinct 40-character ASCII strings:1,000,000 string objects 81.0 MB (81 bytes each: 40-byte object header + 40 chars + 1 NUL byte) tuple of 1,000,000 refs 8.0 MB (8 bytes per reference) set hash table 33.6 MB (2^21 = 2,097,152 slots * 16 bytes for cached hash + pointer) ------------------------------------ Total 122.6 MB (the two indexes add ~41.6 MB, about 51% above raw string objects)In a language where
std::unordered_set<std::string>copies character buffers by default (such as C++), you avoid duplicating text by storing thestd::stringobjects once in astd::vectorand storing indices orstd::string_viewentries in the hash set.Build the collection in one pass
During
__init__, we iterate overstringsonce:- If
textis not yet inseen_strings, we add it toseen_stringsand append it toordered_strings. - If
ordered_stringsis still empty after the loop, we raiseValueErrorright away. - Finally, we convert
ordered_stringsinto an immutabletupleand create a privaterandom.Random()instance if the caller did not supply one.
from typing import Iterable, Optional import random class StringCollection: """Immutable collection of distinct strings supporting O(L) lookup and O(1) uniform sampling.""" def __init__(self, strings: Iterable[str], rng: Optional[random.Random] = None) -> None: # seen_strings: hash set of distinct strings, e.g. {"tcp", "http"}, for fast exact lookup seen_strings = set() # ordered_strings: list of distinct strings in first-seen order, e.g. ["tcp", "http"] ordered_strings = [] # Phase 1: consume the input once (so generators work) and deduplicate by exact value for text in strings: if text not in seen_strings: seen_strings.add(text) ordered_strings.append(text) # Fail immediately on empty input so get_random() never calls randrange(0) later if not ordered_strings: raise ValueError("the collection needs at least one string") # Phase 2: freeze the sequence into a tuple; both containers share references to the same str objects self._index = seen_strings self._items = tuple(ordered_strings) # Keep a private RNG so unit tests are reproducible and global random state cannot interfere if rng is None: rng = random.Random() self._rng = rng- If
Implement `contains` and `get_random`
With both views ready, each query method is two lines:
contains(value)checksvalue in self._index. Python hashes theLcharacters ofvalue, jumps to the matching table slot, and checks exact character equality on a hash match.get_random()callsself._rng.randrange(len(self._items)), which uses rejection sampling under the hood to pick an integer in0 .. n - 1without modulo bias. Since allnentries inself._itemsare distinct, every stored string has probability1 / n.
def contains(self, value: str) -> bool: # Hash-set lookup checks exact string equality in O(L) expected time for length L return value in self._index def get_random(self) -> str: # Every index in 0 .. n - 1 holds a distinct string, so a uniform index gives probability 1 / n random_index = self._rng.randrange(len(self._items)) return self._items[random_index] def __len__(self) -> int: return len(self._items)Compare with a trie-based design
A trie (prefix tree) is a tree where each edge represents a character (or a compressed substring in a radix tree), so strings with a common beginning share the same path from the root:
Strings: "app", "apple", "apply" (root, count=3) --"app"--> [node*, count=3] --"le"--> [node*, count=1] | +--"ly"--> [node*, count=1] (* marks a node where a stored word ends)When comparing our hash-set + tuple design against a trie, separate exact lookup, uniform sampling, prefix queries, and memory:
- Exact lookup (
contains): Both takeO(L)time for a query of lengthL. A trie can stop early on the first mismatched character, whereas a hash set hashes allLcharacters first. In practice, a hash set is usually faster in RAM because hashing scans contiguous bytes in one CPU cache line, while walking a trie chases one pointer per node across scattered memory locations. - Uniform sampling (
get_random): Without a separate array, a trie must storecount(node)— the total number of stored words innode's subtree (includingnodeitself if a word ends there). To sample uniformly, draw a random integerrin0 .. count(node) - 1: if a word ends atnodeandr == 0, stop and return that word (probability1 / count(node)); otherwise subtract1(if a word ended there) and walk into the child whose cumulativecount(child)coversr. That takesO(L * branching)work per sample instead ofO(1). - Prefix queries: If a future requirement asks for
starts_with("https://api/"), a trie finds all matches inO(prefix_length + matches)time, whereas a hash set must scan allnstrings. Since prefix queries are not required here, we do not need that extra machinery. - Memory: In Python, a naive dict-per-node trie uses more memory even when prefixes are shared, because every Python
dictcarries heavy per-object overhead. Measured on CPython 3.13 with100,00040-character URLshttps://example.com/api/v1/users/0000000..0099999(which share 35 of their 40 characters: the 33-character URL path plus two leading zeros"00"):
Python dict-per-node trie 111,146 dict nodes 21.4 MB (214 bytes per string) Python str + set + tuple 100,000 strings 13.1 MB (131 bytes per string)Only a compressed trie (radix tree) with compact node structs in a low-level language like Rust, Go, or C++ beats a hash table on memory when strings share long prefixes.
- Exact lookup (
Walk through Example 1 and complete solution
Trace
StringCollection(["tcp", "http", "tls", "http"]):Input item In seen_strings? seen_strings ordered_strings ---------- ---------------- -------------------------- ----------------------- "tcp" No -> add {"tcp"} ["tcp"] "http" No -> add {"tcp", "http"} ["tcp", "http"] "tls" No -> add {"tcp", "http", "tls"} ["tcp", "http", "tls"] "http" Yes -> skip {"tcp", "http", "tls"} ["tcp", "http", "tls"]self._itemsbecomes("tcp", "http", "tls")withlen == 3.contains("tls")returnsTrue;contains("ht")andcontains("HTTP")returnFalsebecause matching is exact.get_random()drawsrandom_indexfrom{0, 1, 2}with probability1/3each, so"http"is not over-sampled despite appearing twice in the input.
Here is the complete
solution.py:from typing import Iterable, Optional import random class StringCollection: """Immutable collection of distinct strings supporting O(L) lookup and O(1) uniform sampling.""" def __init__(self, strings: Iterable[str], rng: Optional[random.Random] = None) -> None: # seen_strings: hash set of distinct strings, e.g. {"tcp", "http"}, for fast exact lookup seen_strings = set() # ordered_strings: list of distinct strings in first-seen order, e.g. ["tcp", "http"] ordered_strings = [] # Phase 1: consume the input once (so generators work) and deduplicate by exact value for text in strings: if text not in seen_strings: seen_strings.add(text) ordered_strings.append(text) # Fail immediately on empty input so get_random() never calls randrange(0) later if not ordered_strings: raise ValueError("the collection needs at least one string") # Phase 2: freeze the sequence into a tuple; both containers share references to the same str objects self._index = seen_strings self._items = tuple(ordered_strings) # Keep a private RNG so unit tests are reproducible and global random state cannot interfere if rng is None: rng = random.Random() self._rng = rng def contains(self, value: str) -> bool: # Hash-set lookup checks exact string equality in O(L) expected time for length L return value in self._index def get_random(self) -> str: # Every index in 0 .. n - 1 holds a distinct string, so a uniform index gives probability 1 / n random_index = self._rng.randrange(len(self._items)) return self._items[random_index] def __len__(self) -> int: return len(self._items)✅ Submit now — all tests should pass.
Intuition & how it works
Think of organizing a library of prize tickets where you need to do two things instantly: check whether a specific ticket code exists, and draw a random winning ticket fairly. An alphabetical lookup index (like a hash set, a data structure that maps each string's characters to a bucket number for direct lookup) lets you verify whether a ticket exists right away, but its buckets have empty gaps so you cannot say "hand me the 47th ticket." Meanwhile, a numbered shelf (like an array or tuple) lets you roll a die and grab slot 47 in one step, but checking whether a specific code is on the shelf would force you to read every ticket from left to right.
If you keep only a list, every contains(value) call scans all n strings, which slows to a crawl when n is large. If you keep only a hash set, every get_random() call has to copy or walk through all n buckets just to pick one uniformly, turning a single random draw into an O(n) scan. Keeping both structures side by side gives us instant hash lookup and instant random indexing, and because Python stores object references rather than duplicating string characters, the text itself is still stored only once in memory.
For example, suppose we initialize StringCollection(["tcp", "http", "tls", "http"]):
1. We scan the input once, ignoring the second "http", producing _index = {"tcp", "http", "tls"} and _items = ("tcp", "http", "tls").
2. Calling contains("tls") hashes "tls" and finds it in _index in one lookup (True), while contains("ht") misses immediately (False).
3. Calling get_random() picks a uniform integer in 0..2 — say 2 — and returns _items[2], "tls", giving each of the 3 distinct strings a 1/3 chance.
Complexity
Let n be the number of distinct strings, T be the total number of characters across all input strings, and L be the length of a single queried string.
- Initialization time —
O(T)expected: We loop through the input once, hashing every string's characters to checkseen_stringsand appending unseen strings toordered_strings, then copynreferences into a tuple inO(n)time. contains(value)time —O(L)expected: Computing the hash ofvaluereads itsLcharacters once, and on a hit Python compares theLcharacters to confirm an exact match. Pathological hash collisions (different strings landing in the same bucket) could degrade lookup toO(n * L), though CPython randomizes string hash seeds at process startup (PYTHONHASHSEED) to prevent crafted collision attacks.get_random()time —O(1): Generating one random index withrandrange(n)and indexingself._items[random_index]takes constant time regardless of collection size or string length.- Space —
O(T_distinct + n): The distinct string characters are stored once (T_distinctcharacters), while the tuple adds one 8-byte reference per distinct string and the hash set adds one 16-byte hash-table slot per entry (plus table load-factor slack, totaling ~122.6 MB for 1,000,000 40-char ASCII strings on 64-bit CPython 3.13).
Edge cases
- Duplicate input strings:
["tcp", "http", "tls", "http"]stores each distinct protocol once so every stored value is sampled with probability1/3rather than biasing toward repeated entries. - Empty input (
[]or exhausted generator): Validated immediately in__init__and rejected withValueError, rather than lettingrandrange(0)raise an obscure error later. - Empty string member (
[""]):""is a valid string of length 0;bool([""])isTrue, so it is stored, matched bycontains(""), and returned byget_random(). - Single-pass generators: Because
__init__iterates overstringsonly once, passing(line.strip() for line in stream)works without losing data. - Caller mutates the input list later: Copying references into our own
setandtupleisolates the collection from any subsequent edits to the caller's list. - Prefixes, casing, and whitespace:
"ht","HTTP", and"http "all returnFalsewhen"http"is stored because hash-set membership checks exact character-by-character equality.
Common mistakes
- Converting the set to a list inside
get_random(): Writingrandom.choice(list(self._index))allocates and copiesnreferences on every single sample (O(n)per call). Note also thatrandom.sample(some_set, 1)raisesTypeErrorin Python 3.11+. - Using
next(iter(self._index))to "pick any element": Set iteration order is determined by hash slots, not randomness, sonext(iter(...))returns the exact same string on every call. - Building
_itemsbefore deduplicating: Settingself._items = tuple(strings)whileself._index = set(strings)leaves duplicates in_items, biasingget_random()toward strings that appeared multiple times in the input. - Mutating global
random.seed(...)in tests: Seeding the globalrandommodule affects unrelated libraries and makes parallel test runs flaky; injecting a dedicatedrandom.Random(seed)keeps randomness isolated. - Duplicating string bytes in value-semantics languages: In C++ or Rust, storing full
Stringcopies in both aVec<String>and aHashSet<String>doubles character memory; store strings once in the vector and index them by integer position or string slice.
Alternative approaches
- Sorted tuple + binary search (
O(L * log n)lookup,O(1)sample, lower memory): If RAM is the bottleneck, drop the33.6 MBhash set and sort_itemsonce at build time (O(n log n * L)).get_random()is still one random index, andcontains(value)runs binary search (repeatedly halving the sorted search range) inO(L * log n)time — about 20 string comparisons forn = 1,000,000.
import bisect
def sorted_contains(sorted_items, value):
idx = bisect.bisect_left(sorted_items, value)
return idx < len(sorted_items) and sorted_items[idx] == value
- Trie with subtree counts: Store strings character by character in a tree where every node tracks how many stored words live in its subtree. It shines when prefix auto-complete (
starts_with) is needed, at the cost ofO(L * branching)sampling and higher per-node pointer overhead when prefixes are not heavily shared.
Follow-up questions
- How could you extend the data structure to support dynamic
insertandremoveoperations in expected O(1) time without breaking uniform random draws? Replace thesetwith a dictionary_posmapping each string to its current index in a mutable list_items.insert(value)appendsvalueto_itemsand records_pos[value] = len(_items) - 1inO(1)expected time. Toremove(value)inO(1)expected time without leaving gaps in_items, swap the last list element into the deleted element's sloti, update_pos[last_element] = i, andpop()the end of_items:
class MutableStringCollection:
def __init__(self, rng):
self._items = []
self._pos = {}
self._rng = rng
def insert(self, value):
if value in self._pos:
return False
self._pos[value] = len(self._items)
self._items.append(value)
return True
def remove(self, value):
if value not in self._pos:
return False
removed_idx = self._pos.pop(value)
last_value = self._items.pop()
if removed_idx < len(self._items):
self._items[removed_idx] = last_value
self._pos[last_value] = removed_idx
return True
-
What changes if every stored string has a positive numeric weight and
get_random()must sample proportionally to those weights? For an immutable collection with positive weightsw_0, w_1, ..., w_{n-1}, precompute a prefix-sum array (running totals[w_0, w_0 + w_1, ...]), draw a uniform random numberrin[0, total_weight), and binary-search the first prefix sum greater thanrinO(log n)time per draw. If you needO(1)draws on static weights, Walker's alias method (which pairs small-weight and large-weight buckets intonequal-sized two-outcome slots during anO(n)build) samples in constant time. If weights also change dynamically, a Fenwick tree (an array-backed binary index tree that maintains prefix sums under updates) supports both weight updates and weighted draws inO(log n)time. -
Under what workload and language conditions would a radix tree (compressed trie) consume less RAM than a hash table of full strings? A compressed trie (also called a radix tree, which collapses single-child chains of characters into one multi-character edge label) wins when strings share long prefixes and nodes are stored in compact C/Rust structs rather than Python dicts. In a compact 64-bit C layout, storing
nstrings of lengthLin a hash table takes roughlyL + 24bytes per string (8-byte length header +Lchars +16bytes of hash-table pointer overhead at 50% load), while a radix tree with<= 2nnodes of~24bytes each takes roughlyS + 48bytes per string whereSis the unshared suffix length — winning whenever the shared prefixL - Sexceeds ~24 bytes. For example, on1,000,00040-char URLshttps://example.com/api/v1/users/0000000..0999999(34 shared prefix bytes,S ≈ 1byte per node across ~1.11M nodes), a compact radix tree uses ~28 MB versus ~64 MB for a hash table, whereas random UUIDs (S ≈ L) save nothing. -
How should you structure the API and test suite so randomized sampling is deterministic and non-flaky in unit tests? Inject randomness through the constructor (
rngparameter) instead of reading global state. For exact deterministic unit tests, pass a tiny fake object whoserandrange(n)returns a scripted list of indices (verifying boundary indices0andn - 1directly). For statistical uniformity tests, passrandom.Random(42)over tens of thousands of draws and check that observed counts fall within ~4–5 standard deviations (sqrt(draws * p * (1 - p))) of the expected meandraws / n.
Follow-up questions
- How could you extend the data structure to support dynamic `insert` and `remove` operations in expected O(1) time without breaking uniform random draws?
- What changes if every stored string has a positive numeric weight and `get_random()` must sample proportionally to those weights?
- Under what workload and language conditions would a radix tree (compressed trie) consume less RAM than a hash table of full strings?
- How should you structure the API and test suite so randomized sampling is deterministic and non-flaky in unit tests?
Similar questions
- Word Guess Color Scoring
- 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
More Ngrok interview questions
- Word Guess Color Scoring Medium