Simulated Word Store with Prefix Query
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests trie-style prefix counting logic via operation replay, with optional case-insensitive and trailing-digit normalization flags.
Simulated Word Store with Prefix Query
You are building a simple in-memory word store that supports two operations, processed in order as a sequence of commands.
Operations
"insert"— add a word to the store. This operation produces no output (yieldsNonein the result list)."count_with_prefix"— given a prefix string, count how many words currently in the store begin with that prefix. This operation yields an integer in the result list.
You receive two parallel lists:
ops: a list of operation names, each either"insert"or"count_with_prefix".args: a list of single-element lists, whereargs[i]holds the argument forops[i].
Process every operation in order and return a list of results in the same order. Insert results are None; query results are integers.
Normalization flags
Two optional boolean flags change how words and prefixes are stored and matched:
case_insensitive— whenTrue, apply Unicode case-folding (str.casefold()) to every word before inserting and to every prefix before querying.strip_trailing_digits— whenTrue, remove any trailing run of decimal digits from a word or prefix before inserting or querying (e.g."item42"becomes"item";"4ever"stays"4ever").
When both flags are True, trailing digits are stripped first, then case-folding is applied. The same transformation must be used for both inserts and queries — normalization is applied to the argument before it is stored or looked up.
Duplicate inserts count separately. Inserting the same (post-normalization) word twice means a query for its prefix returns at least 2.
Prefix matching uses str.startswith. An empty prefix matches every stored word.
Constraints
1 ≤ len(ops) == len(args) ≤ 1 000- Each
args[i]is a list containing exactly one non-empty string. - Every string consists of printable Unicode characters.
ops[i]is either"insert"or"count_with_prefix".case_insensitiveandstrip_trailing_digitsare booleans (defaultFalse).- The result list has the same length as
ops. Insert positions areNone; query positions are non-negative integers.
Examples
Example 1
Input: prefix_search(['insert', 'insert', 'count_with_prefix', 'count_with_prefix', 'insert', 'count_with_prefix'], [['apple'], ['app'], ['app'], ['apple'], ['application'], ['ap']])
Output: [None, None, 2, 1, None, 3]
Example 2
Input: prefix_search(['insert', 'count_with_prefix', 'insert', 'count_with_prefix'], [['Report123'], ['report'], ['REPORT456'], ['report'], True, True])
Output: [None, 0, None, 0]
Hints
Hint 1
Keep a plain list of normalized words. For each count_with_prefix query, scan the list and count words where word.startswith(normalized_prefix) is True — no fancy data structure needed at this scale.
Hint 2
The normalization flags must be applied to both inserts and queries using exactly the same helper function. Write it once and call it in both branches.
Hint 3
Watch the order of normalization steps: strip trailing digits with re.sub(r'\d+$', '', s) before applying casefold(). An empty string after stripping is valid — just store or query it as-is.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is straightforward: maintain a plain list of normalized words and answer each prefix query by scanning that list.
Why a list is fine here
The constraints cap the operation count at 1 000. A linear scan for each query gives at most 1 000 × 1 000 = 1 000 000 startswith checks — well within budget. A trie with per-node counts would reduce query time to O(prefix length), but it adds implementation complexity that the problem does not require.
Normalization
Both flags must pass through a single normalize helper called identically on insert arguments and query arguments. Getting this wrong — normalizing on insert but not on query, or vice versa — means stored keys and lookup keys live in different spaces and matches silently fail.
Order matters when both flags are active: strip trailing digits first with re.sub(r"\d+$", "", s), then apply casefold(). The $ anchor ensures only a trailing digit run is removed, so "4ever" is untouched while "item42" becomes "item". casefold() is preferred over lower() for Unicode correctness (e.g. German "ß" case-folds to "ss").
Duplicate counting
Inserting the same normalized word twice appends it to the list twice, so a matching query correctly returns a count of at least 2. No deduplication is performed.
Empty prefix
"".startswith("") is True for every string in Python, so an empty prefix (or a word that normalizes to "") counts all stored words, which is the correct behavior.
Complexity
- Each
insert: O(L) for normalization, O(1) to append — total O(L). - Each
count_with_prefix: O(N · max(L, P)) where N is the current store size, L is the average word length, and P is the prefix length. - Overall: O(Q · N · L) in the worst case, which is O(10^6) for the given constraints.
- Space: O(N · L) for the stored words.
Full solution
import re
from typing import List, Optional
def prefix_search(
ops: List[str],
args: List[List[str]],
case_insensitive: bool = False,
strip_trailing_digits: bool = False,
) -> List[Optional[int]]:
_trailing_digits = re.compile(r"\d+$")
def normalize(value: str) -> str:
if strip_trailing_digits:
value = _trailing_digits.sub("", value)
if case_insensitive:
value = value.casefold()
return value
store: List[str] = []
results: List[Optional[int]] = []
for op, arg in zip(ops, args):
word = normalize(arg[0])
if op == "insert":
store.append(word)
results.append(None)
elif op == "count_with_prefix":
results.append(sum(w.startswith(word) for w in store))
else:
raise ValueError(f"Unknown operation: {op!r}")
return results