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: Consume strings (which may be a list, set, or single-pass generator), deduplicate repeated values so each distinct string is kept once, and raise ValueError immediately if no strings were supplied. Subsequent changes to the caller's input container must not affect the collection. When rng is provided, use it for all random draws; otherwise create an independent random.Random instance.
  • contains(self, value: str) -> bool: Return True when value matches a stored string character-for-character, and False otherwise. 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 probability 1 / n of being selected, regardless of how many duplicate copies appeared in strings.
  • __len__(self) -> int: Return n, 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 1 string must be yielded by strings; empty iterables ([], set(), exhausted generators) must raise ValueError.
  • Individual strings may have length 0 ("") or arbitrary ASCII/Unicode text, and the collection may hold up to 10^6 distinct strings where both string payload and index memory matter.
  • contains(value) must run in O(L) expected time for a query string of length L, and get_random() must run in O(1) time per draw.
  • No insertions or removals occur after __init__ completes.

Step-by-step walkthrough

  1. 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: return True if value is an exact match for a stored string, and False otherwise.
    • get_random() -> str: return one stored string so that every stored string has the exact same 1 / n chance of being picked, where n is 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 probability 1/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 ValueError in __init__ when no strings are given fails fast instead of crashing later inside get_random().
    • Reproducible randomness. Accepting an optional random.Random instance lets unit tests pass a fixed seed without touching Python's global random module.
  2. 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, so get_random() just picks a random index in O(1) time. However, contains(value) has to compare value against up to all n strings one by one, taking O(n * L) time in the worst case for strings of length L.
    • 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" in O(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,000 strings and 100,000 calls to get_random(), copying the set on each call visits 10^11 slots. We need both operations to be fast at the same time.

  3. 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:

    1. self._index (a set) maps each string's content to its hash bucket so contains(value) runs in O(L) expected time.
    2. self._items (a tuple) assigns each distinct string a dense integer index 0, 1, ..., n - 1 so get_random() picks one random integer and indexes in O(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 str objects 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) for 1,000,000 distinct 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 the std::string objects once in a std::vector and storing indices or std::string_view entries in the hash set.

  4. Build the collection in one pass

    During __init__, we iterate over strings once:

    • If text is not yet in seen_strings, we add it to seen_strings and append it to ordered_strings.
    • If ordered_strings is still empty after the loop, we raise ValueError right away.
    • Finally, we convert ordered_strings into an immutable tuple and create a private random.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
    
  5. Implement `contains` and `get_random`

    With both views ready, each query method is two lines:

    • contains(value) checks value in self._index. Python hashes the L characters of value, jumps to the matching table slot, and checks exact character equality on a hash match.
    • get_random() calls self._rng.randrange(len(self._items)), which uses rejection sampling under the hood to pick an integer in 0 .. n - 1 without modulo bias. Since all n entries in self._items are distinct, every stored string has probability 1 / 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)
    
  6. 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:

    1. Exact lookup (contains): Both take O(L) time for a query of length L. A trie can stop early on the first mismatched character, whereas a hash set hashes all L characters 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.
    2. Uniform sampling (get_random): Without a separate array, a trie must store count(node) — the total number of stored words in node's subtree (including node itself if a word ends there). To sample uniformly, draw a random integer r in 0 .. count(node) - 1: if a word ends at node and r == 0, stop and return that word (probability 1 / count(node)); otherwise subtract 1 (if a word ended there) and walk into the child whose cumulative count(child) covers r. That takes O(L * branching) work per sample instead of O(1).
    3. Prefix queries: If a future requirement asks for starts_with("https://api/"), a trie finds all matches in O(prefix_length + matches) time, whereas a hash set must scan all n strings. Since prefix queries are not required here, we do not need that extra machinery.
    4. Memory: In Python, a naive dict-per-node trie uses more memory even when prefixes are shared, because every Python dict carries heavy per-object overhead. Measured on CPython 3.13 with 100,000 40-character URLs https://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.

  7. 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._items becomes ("tcp", "http", "tls") with len == 3.
    • contains("tls") returns True; contains("ht") and contains("HTTP") return False because matching is exact.
    • get_random() draws random_index from {0, 1, 2} with probability 1/3 each, 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 check seen_strings and appending unseen strings to ordered_strings, then copy n references into a tuple in O(n) time.
  • contains(value) time — O(L) expected: Computing the hash of value reads its L characters once, and on a hit Python compares the L characters to confirm an exact match. Pathological hash collisions (different strings landing in the same bucket) could degrade lookup to O(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 with randrange(n) and indexing self._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_distinct characters), 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 probability 1/3 rather than biasing toward repeated entries.
  • Empty input ([] or exhausted generator): Validated immediately in __init__ and rejected with ValueError, rather than letting randrange(0) raise an obscure error later.
  • Empty string member ([""]): "" is a valid string of length 0; bool([""]) is True, so it is stored, matched by contains(""), and returned by get_random().
  • Single-pass generators: Because __init__ iterates over strings only once, passing (line.strip() for line in stream) works without losing data.
  • Caller mutates the input list later: Copying references into our own set and tuple isolates the collection from any subsequent edits to the caller's list.
  • Prefixes, casing, and whitespace: "ht", "HTTP", and "http " all return False when "http" is stored because hash-set membership checks exact character-by-character equality.

Common mistakes

  • Converting the set to a list inside get_random(): Writing random.choice(list(self._index)) allocates and copies n references on every single sample (O(n) per call). Note also that random.sample(some_set, 1) raises TypeError in Python 3.11+.
  • Using next(iter(self._index)) to "pick any element": Set iteration order is determined by hash slots, not randomness, so next(iter(...)) returns the exact same string on every call.
  • Building _items before deduplicating: Setting self._items = tuple(strings) while self._index = set(strings) leaves duplicates in _items, biasing get_random() toward strings that appeared multiple times in the input.
  • Mutating global random.seed(...) in tests: Seeding the global random module affects unrelated libraries and makes parallel test runs flaky; injecting a dedicated random.Random(seed) keeps randomness isolated.
  • Duplicating string bytes in value-semantics languages: In C++ or Rust, storing full String copies in both a Vec<String> and a HashSet<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 the 33.6 MB hash set and sort _items once at build time (O(n log n * L)). get_random() is still one random index, and contains(value) runs binary search (repeatedly halving the sorted search range) in O(L * log n) time — about 20 string comparisons for n = 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 of O(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 insert and remove operations in expected O(1) time without breaking uniform random draws? Replace the set with a dictionary _pos mapping each string to its current index in a mutable list _items. insert(value) appends value to _items and records _pos[value] = len(_items) - 1 in O(1) expected time. To remove(value) in O(1) expected time without leaving gaps in _items, swap the last list element into the deleted element's slot i, update _pos[last_element] = i, and pop() 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 weights w_0, w_1, ..., w_{n-1}, precompute a prefix-sum array (running totals [w_0, w_0 + w_1, ...]), draw a uniform random number r in [0, total_weight), and binary-search the first prefix sum greater than r in O(log n) time per draw. If you need O(1) draws on static weights, Walker's alias method (which pairs small-weight and large-weight buckets into n equal-sized two-outcome slots during an O(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 in O(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 n strings of length L in a hash table takes roughly L + 24 bytes per string (8-byte length header + L chars + 16 bytes of hash-table pointer overhead at 50% load), while a radix tree with <= 2n nodes of ~24 bytes each takes roughly S + 48 bytes per string where S is the unshared suffix length — winning whenever the shared prefix L - S exceeds ~24 bytes. For example, on 1,000,000 40-char URLs https://example.com/api/v1/users/0000000 .. 0999999 (34 shared prefix bytes, S ≈ 1 byte 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 (rng parameter) instead of reading global state. For exact deterministic unit tests, pass a tiny fake object whose randrange(n) returns a scripted list of indices (verifying boundary indices 0 and n - 1 directly). For statistical uniformity tests, pass random.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 mean draws / n.

Follow-up questions

Similar questions

More Ngrok interview questions

All 2 Ngrok questions →