Fast Word Membership Lookup at Scale

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You are given a vocabulary list dictionary containing distinct strings and a list of lookup strings queries. Implement check_dictionary_words(dictionary: List[str], queries: List[str]) -> List[bool] to return a boolean list of length len(queries), where element i is True if queries[i] matches a string in dictionary and False otherwise.

Matching follows strict exact equality: - Comparisons are case-sensitive ("Atlas" does not match "atlas"), with no whitespace stripping or character folding. - The empty string "" is a normal string and evaluates to True if and only if "" appears in dictionary. - Repeated entries in queries must each produce a boolean at their original index in the returned list.

Because dictionary can contain up to 1,000,000 unique terms and queries can contain up to 100,000 lookups, structure your implementation for high lookup throughput and modest memory overhead.

Examples

Example 1

Input:
  dictionary = ["cobalt", "nickel", "zinc", "copper"]
  queries = ["zinc", "iron", "cobalt", "zinc"]
Output:
  [True, False, True, True]

Walk-through: "zinc" and "cobalt" appear in dictionary, "iron" is absent, and the second occurrence of "zinc" at index 3 produces True again in query order.

Example 2

Input:
  dictionary = ["Atlas", "metric", "pulse"]
  queries = ["atlas", "pulse", "", " pulse"]
Output:
  [False, True, False, False]

Walk-through: "atlas" differs from "Atlas" in letter case (False), "pulse" matches (True), and neither "" nor " pulse" (with a leading space) appears in dictionary (False).

Constraints

  • 0 <= len(dictionary) <= 1,000,000
  • Every string in dictionary is unique.
  • 0 <= len(queries) <= 100,000
  • Strings in dictionary and queries may be empty ("") and may contain spaces, mixed case, or arbitrary Unicode characters.

Step-by-step walkthrough

  1. Understand the scale and exact-match rules

    We receive two string lists: - dictionary: up to 1,000,000 unique terms, provided once up front. - queries: up to 100,000 strings to test, returning a List[bool] of the exact same length and order.

    Before choosing a data structure, check the examples to pin down what counts as a match: - In Example 2, 'Atlas' is in dictionary while query 'atlas' returns False, so matching is case-sensitive with no whitespace trimming (' pulse' also returns False). - Query '' (the empty string) returns False simply because '' is not in that dictionary—it is a valid string query, not an error. - Duplicate queries (like 'zinc' appearing twice in Example 1) must each produce a boolean at their respective positions in the output list.

  2. Why scanning the list for every query times out

    In Python, writing query in dictionary when dictionary is a list looks deceptively short, yet under the hood Python compares query against dictionary[0], dictionary[1], and so on until it either finds a match or hits the end:

    def slow_check(dictionary: List[str], queries: List[str]) -> List[bool]:
        results = []
        for query in queries:
            # Linear scan on a list: inspects up to len(dictionary) words per query!
            results.append(query in dictionary)
        return results
    

    When a query is absent, that scan checks all 1,000,000 words. Across 100,000 queries, 10^6 * 10^5 = 10^11 string comparisons would take minutes instead of milliseconds. Because dictionary does not change between queries, we should pay a one-time preprocessing step to make every lookup fast.

  3. Key insight: preprocess once into a hash set (and compare memory trade-offs)

    Converting dictionary into a Python set builds an open-addressed hash table once. To look up a query of length L, Python computes its hash from its L characters and jumps directly to the matching table slot in O(L) average time—completely independent of whether the dictionary holds 10 words or 1,000,000 words!

    Crucially, set(dictionary) does not copy the string characters: each slot only stores an 8-byte cached hash and an 8-byte pointer back to the existing str object already in memory:

    Existing str objects in memory:    "Atlas"           "metric"       "pulse"
                                          ^                 ^              ^
    word_set hash table slots:      [ ... | (h1, ptr) | ... | (h2, ptr) | (h3, ptr) | ... ]
                                                                           ^
    Query "pulse" -> hash("pulse") == h3 ----------------------------------+  (1 hash + 1 check -> True!)
    Query "atlas" -> hash("atlas") -----------------> lands on empty slot -> False!
    

    How does a set compare against other candidate structures for 1,000,000 words on 64-bit Python? - Hash set (chosen): ~33.6 MB (32 MiB: 2^21 slots × 16 bytes so the table stays under ~60% load), O(L) average lookup. Best balance of speed, simplicity, and modest pointer-only overhead. - Sorted list + binary search (bisect): Only 8.0 MB (7.6 MiB) of extra pointers, but costs O(D log D) string comparisons to sort and ~20 (log2(10^6)) string comparisons per query. Choose when RAM is severely constrained. - Trie (prefix tree of nested dicts): Allocates one Python dict object per character node—hundreds of megabytes for 10^6 words! Worthwhile only when prefix/autocomplete queries are required. - Bloom filter: Compact bit array (~1.25 MB at 10 bits/word gives ~0.8% false positives), useful in front of disk storage, but cannot be used alone because false positives violate exact bool answers.

  4. Handle case sensitivity, Unicode normalization, and duplicate queries

    In an interview discussion, three real-world string nuances come up right away. The golden rule is symmetry: whatever transformation you choose, apply the exact same function when building word_set and when testing each query.

    1. Case sensitivity: Our judged function keeps exact case ("Atlas" != "atlas"). If a caller needed case-insensitive lookups, transform both sides with .casefold() (preferred over .lower() for international text because "Straße".casefold() becomes "strasse").
    2. Unicode normalization: Visually identical text like "café" can be encoded either as one precomposed character (U+00E9) or as 'e' followed by a combining acute accent (U+0301). Raw string equality treats those two code-point sequences as unequal. When canonical equivalence is desired, normalize both sides with unicodedata.normalize("NFC", text)—normalizing only one side causes identical-looking words to miss!
    3. Duplicate queries: Every query receives its own boolean in results. For an in-memory set, adding a separate query_cache dictionary would actually slow things down, because checking query in query_cache does the exact same hash computation as query in word_set while wasting extra memory. Deduplicating unique queries first only pays off when each lookup crosses a slow network or disk boundary.
  5. Trace the examples step by step

    Let's trace both examples through the two phases (build word_set once outside the loop, then check each query):

    Example 1:
      dictionary = ['cobalt', 'nickel', 'zinc', 'copper']
      word_set   = {'cobalt', 'nickel', 'zinc', 'copper'}
      queries:
        'zinc'   in word_set -> True
        'iron'   in word_set -> False
        'cobalt' in word_set -> True
        'zinc'   in word_set -> True   (repeated query answered again in order)
      results = [True, False, True, True]
    
    Example 2:
      dictionary = ['Atlas', 'metric', 'pulse']
      word_set   = {'Atlas', 'metric', 'pulse'}
      queries:
        'atlas'  in word_set -> False  (capital 'A' vs lowercase 'a')
        'pulse'  in word_set -> True
        ''       in word_set -> False  (empty string not in word_set)
        ' pulse' in word_set -> False  (leading space not stripped)
      results = [False, True, False, False]
    
  6. Complete solution

    Putting both phases together—making sure set(dictionary) sits outside the query loop—gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def check_dictionary_words(dictionary: List[str], queries: List[str]) -> List[bool]:
        # Phase 1: Preprocess the dictionary into a hash set once.
        # word_set: set of exact dictionary strings, e.g. {"cobalt", "nickel", "zinc"}.
        # Python sets store references to existing str objects rather than duplicating
        # character buffers, keeping memory overhead small while enabling fast hash lookup.
        word_set: Set[str] = set(dictionary)
    
        # Phase 2: Answer every query in original order using exact membership testing.
        # Matching is case-sensitive ("Atlas" != "atlas") with no trimming or normalization.
        results: List[bool] = []
        for query in queries:
            is_present = query in word_set
            results.append(is_present)
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine checking 100,000 requested usernames against a roster of 1,000,000 reserved names printed in random order on a paper scroll. Reading the scroll from top to bottom for every single lookup would take forever; instead, if you first file each reserved name into a numbered cubbyhole computed directly from its characters—a hash set (a collection backed by an array of buckets indexed by a fast mathematical fingerprint of each item)—every lookup jumps straight to one cubbyhole in a single step.

Leaving dictionary as a Python list makes query in dictionary perform a linear scan of up to 1,000,000 strings per query. Across 100,000 queries, missed lookups alone can trigger 10^11 string comparisons. Building word_set = set(dictionary) once up front hashes each dictionary word a single time and reuses references to the existing str objects in memory (avoiding duplicate character copies), turning each query into one hash calculation and an O(1) slot probe on average.

Walk through Example 2 with dictionary = ['Atlas', 'metric', 'pulse'] and queries = ['atlas', 'pulse', '', ' pulse']: 1. Build word_set = {'Atlas', 'metric', 'pulse'} once before looping. 2. Check 'atlas': its hash differs from 'Atlas' (matching is case-sensitive), so append False. 3. Check 'pulse': lands on 'pulse''s slot and matches character-for-character, so append True. 4. Check '' and ' pulse': neither appears in word_set, so append False twice and return [False, True, False, False].

Complexity

Let D be the number of words in dictionary, Q be the number of strings in queries, S_D be the total characters across all dictionary words, and S_Q be the total characters across all queries.

  • Time: O(S_D + S_Q) average (equivalently O((D + Q) * L) when average word length is L). Constructing set(dictionary) hashes each of the D strings once (O(S_D)), and each of the Q membership tests hashes one query string and probes an average of O(1) hash-table slots (O(S_Q)). Worst-case hash collisions (two distinct strings landing in the same slot) are guarded against in Python by per-process randomized SipHash seeds.
  • Space: O(D) auxiliary memory for word_set plus O(Q) for the returned results list. Because word_set stores pointers to the existing string objects rather than copying their text, 1,000,000 entries use only ~33.6 MB (32 MiB: 2^21 slots × 16 bytes) for the hash table on 64-bit CPython.

Edge cases

  • Empty dictionary (dictionary = []): word_set is empty and every query returns False.
  • Empty query list (queries = []): Returns [].
  • Empty string "": Treated like any normal string—returns True if and only if "" is in dictionary.
  • Duplicate queries (["zinc", "iron", "cobalt", "zinc"]): Preserves exact length and positional order ([True, False, True, True]); no separate cache is needed in RAM because word_set already answers in one hash lookup.
  • Case sensitivity ("Atlas" vs "atlas", "Straße" vs "strasse"): Exact code-point matching keeps different capitalizations distinct unless case folding (converting strings to a canonical caseless form via .casefold()) is explicitly requested on both sides.
  • Substrings and whitespace ("app", "apples", " pulse" vs "pulse"): Neither prefix matching nor .strip() trimming is performed.
  • Unicode characters ("café", "naïve"): Matched by exact Unicode code points; if precomposed (U+00E9) and decomposed ('e' + U+0301) spellings should match, apply Unicode normalization (converting equivalent character sequences to a standard form such as unicodedata.normalize("NFC", s)) to both dictionary and queries.

Common mistakes

  • Running query in dictionary directly on the input list: Looks clean in Python but silently executes an O(D) linear scan per query (O(D * Q) total).
  • Writing query in set(dictionary) inside the for loop: Rebuilds the entire million-word set on every single query, costing O(D * Q) again!
  • Calling .lower() or .strip() without being asked: Breaks case-sensitive words like Example 2 ('Atlas' vs 'atlas') and whitespace-distinct tokens (' pulse').
  • Normalizing only queries (or only the dictionary): If you normalize queries with .casefold() or NFC while leaving 'Atlas' raw in word_set, 'Atlas' will not even match 'Atlas'!
  • Deduplicating queries with list(set(queries)): Destroys both the length and the order of the output boolean list.
  • Sorting dictionary.sort() in place for binary search: Mutates the caller's input list unexpectedly; always use sorted(dictionary) if taking the binary-search route.

Alternative approaches

  • Sorted copy + binary search (bisect_left): Binary search repeatedly halves a sorted array to locate a target in O(log D) comparisons. Sorting sorted_words = sorted(dictionary) uses only 8.0 MB (7.6 MiB) of pointer storage for 10^6 words (4x smaller table overhead than set), at the cost of O(D log D) build comparisons and ~20 string comparisons per query instead of 1 hash.
  • Trie (prefix tree): A trie stores strings along shared character-by-character paths from a root node. While lookups take O(L) steps and naturally support prefix searches, representing each node as a Python dict consumes an order of magnitude more RAM than set(dictionary) for exact-word matching.
  • Bloom filter + disk store: A Bloom filter is a compact bit array set by multiple hash functions that can say "definitely not in set" with zero false negatives or "probably in set" with a small tunable false-positive rate (~0.8% at 10 bits/word, ~1.25 MB for 10^6 words). Alone it violates exact boolean output, but paired in front of an on-disk table it filters out >99% of misses in RAM.

Follow-up questions

  • How would you scale membership lookups if the vocabulary contained billions of terms and exceeded a single machine's memory? Partition both the vocabulary and incoming query batches across K shard nodes (or sorted on-disk SSTable files) using a deterministic hash function such as zlib.crc32(word.encode("utf-8")) % K—never Python's built-in hash(), whose random per-process seed varies across processes! Deduplicate repeated queries within each batch before issuing network RPCs so each distinct string is queried once and mapped back to its original positions, and place an in-memory Bloom filter on each shard to reject >99% of misses before reading disk.
  • How would your choice of data structure handle frequent word insertions and deletions interleaved with query batches? A Python set natively supports word_set.add(word) and word_set.discard(word) in O(L) average time, whereas a sorted array for binary search would suffer O(D) element shifts per insertion or deletion. When background mutations run concurrently alongside read threads, protect mutations with a reader-writer lock (or shard the hash table into striped locks by bucket) or publish copy-on-write snapshots when writes arrive in periodic batches.
  • How would you adapt the design if callers also needed fast prefix checks such as has_prefix(prefix) or case-folded Unicode matching? Hash sets scramble lexicographic order and cannot answer has_prefix without scanning all D terms; instead, store sorted_words = sorted(dictionary), find idx = bisect.bisect_left(sorted_words, prefix) in O(log D) comparisons, and check idx < len(sorted_words) and sorted_words[idx].startswith(prefix) (or use a compact radix tree / DAWG if enumerating completions). To support caseless Unicode equivalence on either structure, define a canonicalizer canon(s) = unicodedata.normalize("NFC", s).casefold() and apply canon symmetrically to every vocabulary entry at build time and every query or prefix at lookup time.

Follow-up questions

Similar questions

More Reevo interview questions

All 3 Reevo questions →