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
dictionaryis unique. 0 <= len(queries) <= 100,000- Strings in
dictionaryandqueriesmay be empty ("") and may contain spaces, mixed case, or arbitrary Unicode characters.
Step-by-step walkthrough
Understand the scale and exact-match rules
We receive two string lists: -
dictionary: up to1,000,000unique terms, provided once up front. -queries: up to100,000strings to test, returning aList[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 indictionarywhile query'atlas'returnsFalse, so matching is case-sensitive with no whitespace trimming (' pulse'also returnsFalse). - Query''(the empty string) returnsFalsesimply 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.Why scanning the list for every query times out
In Python, writing
query in dictionarywhendictionaryis alistlooks deceptively short, yet under the hood Python comparesqueryagainstdictionary[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 resultsWhen a query is absent, that scan checks all
1,000,000words. Across100,000queries,10^6 * 10^5 = 10^11string comparisons would take minutes instead of milliseconds. Becausedictionarydoes not change between queries, we should pay a one-time preprocessing step to make every lookup fast.Key insight: preprocess once into a hash set (and compare memory trade-offs)
Converting
dictionaryinto a Pythonsetbuilds an open-addressed hash table once. To look up a query of lengthL, Python computes its hash from itsLcharacters and jumps directly to the matching table slot inO(L)average time—completely independent of whether the dictionary holds10words or1,000,000words!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 existingstrobject 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
setcompare against other candidate structures for1,000,000words on 64-bit Python? - Hashset(chosen): ~33.6 MB(32 MiB:2^21slots ×16bytes so the table stays under ~60% load),O(L)average lookup. Best balance of speed, simplicity, and modest pointer-only overhead. - Sortedlist+ binary search (bisect): Only8.0 MB(7.6 MiB) of extra pointers, but costsO(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 nesteddicts): Allocates one Pythondictobject per character node—hundreds of megabytes for10^6words! Worthwhile only when prefix/autocomplete queries are required. - Bloom filter: Compact bit array (~1.25 MBat10bits/word gives ~0.8%false positives), useful in front of disk storage, but cannot be used alone because false positives violate exactboolanswers.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_setand when testing eachquery.- 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"). - 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 withunicodedata.normalize("NFC", text)—normalizing only one side causes identical-looking words to miss! - Duplicate queries: Every query receives its own boolean in
results. For an in-memoryset, adding a separatequery_cachedictionary would actually slow things down, because checkingquery in query_cachedoes the exact same hash computation asquery in word_setwhile wasting extra memory. Deduplicating unique queries first only pays off when each lookup crosses a slow network or disk boundary.
- Case sensitivity: Our judged function keeps exact case (
Trace the examples step by step
Let's trace both examples through the two phases (build
word_setonce outside the loop, then check eachquery):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]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 isL). Constructingset(dictionary)hashes each of theDstrings once (O(S_D)), and each of theQmembership 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_setplus O(Q) for the returnedresultslist. Becauseword_setstores pointers to the existing string objects rather than copying their text,1,000,000entries use only~33.6 MB(32 MiB:2^21slots ×16bytes) for the hash table on 64-bit CPython.
Edge cases
- Empty dictionary (
dictionary = []):word_setis empty and every query returnsFalse. - Empty query list (
queries = []): Returns[]. - Empty string
"": Treated like any normal string—returnsTrueif and only if""is indictionary. - Duplicate queries (
["zinc", "iron", "cobalt", "zinc"]): Preserves exact length and positional order ([True, False, True, True]); no separate cache is needed in RAM becauseword_setalready 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 asunicodedata.normalize("NFC", s)) to bothdictionaryandqueries.
Common mistakes
- Running
query in dictionarydirectly on the inputlist: Looks clean in Python but silently executes an O(D) linear scan per query (O(D * Q)total). - Writing
query in set(dictionary)inside theforloop: Rebuilds the entire million-word set on every single query, costingO(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
querieswith.casefold()orNFCwhile leaving'Atlas'raw inword_set,'Atlas'will not even match'Atlas'! - Deduplicating
querieswithlist(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 usesorted(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. Sortingsorted_words = sorted(dictionary)uses only8.0 MB(7.6 MiB) of pointer storage for10^6words (4x smaller table overhead thanset), at the cost ofO(D log D)build comparisons and~20string 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 Pythondictconsumes an order of magnitude more RAM thanset(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%at10bits/word, ~1.25 MBfor10^6words). 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
Kshard nodes (or sorted on-disk SSTable files) using a deterministic hash function such aszlib.crc32(word.encode("utf-8")) % K—never Python's built-inhash(), 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
setnatively supportsword_set.add(word)andword_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_prefixwithout scanning allDterms; instead, storesorted_words = sorted(dictionary), findidx = bisect.bisect_left(sorted_words, prefix)in O(log D) comparisons, and checkidx < 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 canonicalizercanon(s) = unicodedata.normalize("NFC", s).casefold()and applycanonsymmetrically to every vocabulary entry at build time and every query or prefix at lookup time.
Follow-up questions
- How would you scale membership lookups if the vocabulary contained billions of terms and exceeded a single machine's memory?
- How would your choice of data structure handle frequent word insertions and deletions interleaved with query batches?
- How would you adapt the design if callers also needed fast prefix checks such as has_prefix(prefix) or case-folded Unicode matching?
Similar questions
- Palindromic Substring Count
- Top Teams from a Paginated HTTP Endpoint
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance