Prefix Match Counter with Normalization
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a batch prefix-query engine prefix_search that maintains a collection of strings and answers prefix-count queries under configurable text normalization rules.
You are given two parallel lists, operations and arguments, along with two boolean flags (case_insensitive and strip_trailing_digits, both defaulting to False). For each index i from 0 to len(operations) - 1, operations[i] specifies the command and arguments[i][0] provides its string input:
"insert": Insertsarguments[i][0]into the collection and appendsNoneto the returned list. Duplicate insertions are retained and counted separately."count_with_prefix": Counts how many strings inserted so far begin with the prefixarguments[i][0]and appends that integer count to the returned list. An empty string""is a prefix of every string (including"").
Before storing a word or searching for a prefix, apply the active normalization flags in order to both inserted words and queried prefixes:
case_insensitive: WhenTrue, convert letters to lowercase (text.lower()) so uppercase and lowercase variants match identically.strip_trailing_digits: WhenTrue, use a regular expression to remove any contiguous run of ASCII digits ('0'–'9') located strictly at the very end of the string. Digits followed by any non-digit character (including a trailing newline"\n") must remain untouched, while a string consisting solely of digits normalizes to"".
If arguments contains extra trailing elements beyond len(operations), ignore those extra elements and process only the len(operations) commands.
def prefix_search(
operations: List[str],
arguments: List[List[str]],
case_insensitive: bool = False,
strip_trailing_digits: bool = False,
) -> List[Optional[int]]:
pass
Examples
Example 1
operations = [
"insert",
"insert",
"count_with_prefix",
"insert",
"count_with_prefix",
"count_with_prefix",
]
arguments = [["spark"], ["spa"], ["spa"], ["space"], ["sp"], ["sparkle"]]
# case_insensitive = False, strip_trailing_digits = False
# Output: [None, None, 2, None, 3, 0]
Walk-through: After inserting "spark" and "spa", both begin with "spa" (count 2). After inserting "space", all three stored strings begin with "sp" (count 3), while none begin with "sparkle" (count 0).
Example 2
operations = [
"insert",
"insert",
"insert",
"count_with_prefix",
"count_with_prefix",
]
arguments = [["Sensor42"], ["SENSOR007"], ["v2Node9"], ["sensor"], ["v2node99"]]
case_insensitive = True
strip_trailing_digits = True
# Output: [None, None, None, 2, 1]
Walk-through: With both flags active, "Sensor42" and "SENSOR007" both normalize to "sensor", while "v2Node9" keeps its interior '2' and normalizes to "v2node". Querying "sensor" matches 2 entries, and querying "v2node99" normalizes to "v2node", matching 1 entry.
Constraints
0 <= len(operations) <= 5 * 10^4len(arguments) >= len(operations)- Each
operations[i]is either"insert"or"count_with_prefix". - For every
0 <= i < len(operations),arguments[i]is a non-empty list whose first itemarguments[i][0]is a string. - The sum of
len(arguments[i][0])across all commands is at most2 * 10^5.
Step-by-step walkthrough
Understand the operations and normalization rules
We are building a batch prefix counter supporting two commands passed via parallel lists
operationsandarguments:"insert": addsarguments[i][0]to our collection and appendsNoneto the output list."count_with_prefix": counts how many previously added strings begin witharguments[i][0]and appends that count to the output list.
Two optional flags apply to both inserted strings and queried prefixes:
case_insensitive: folds letters to lowercase so"Sensor"and"SENSOR"match"sensor".strip_trailing_digits: uses a regular expression to delete any run of ASCII digits at the very end of the string, turning"Sensor42"into"Sensor"while keeping interior digits in"v2Node9"(-> "v2Node").
Keep two subtle input rules in mind: - Duplicate insertions are counted individually (inserting
"sensor"twice means two stored strings start with"sensor"), and the empty prefix""matches every stored string. -argumentsmay contain extra trailing entries pastlen(operations), so pairing the two lists withzip(operations, arguments)stops cleanly atlen(operations).Why scanning a plain list is too slow
A straightforward brute-force approach appends each normalized word to a list on
"insert"and scans the entire list callingword.startswith(prefix)on every"count_with_prefix"query.Although insertion is
O(1), each query inspects allWstored words and compares up toPcharacters per word (O(W * P)time). With20,000insertions followed by20,000queries, that executes400,000,000string checks — repeatedly re-comparing shared prefixes like"sp"across"spa","spark", and"space"on every single query.Store pass-through counts in a trie
To share common prefixes, we organize normalized strings in a trie (prefix tree), where each edge represents a single character and each node represents the prefix spelled from the root down to that node.
If nodes only marked where whole words end,
count_with_prefix("sp")would still have to traverse the entire subtree beneath"sp"to sum all word endings. Instead, we maintain an integerprefix_countdirectly on every node, tracking how many inserted words pass through that node:After inserting "spark", "spa", and "space": (root, count=3) └── 's' (count=3) └── 'p' (count=3) └── 'a' (count=3) <-- "spa" ends here; 3 words share "spa" ├── 'r' (count=1) -> 'k' (count=1) └── 'c' (count=1) -> 'e' (count=1)Now both commands run in time proportional solely to the length
Lof the single string being processed: - Oninsert(word), incrementroot.prefix_countand step character by character, creating missing child nodes and adding1to each visited node'sprefix_count. - Oncount_with_prefix(prefix), step down the characters ofprefix; if any edge is missing return0, otherwise return the final node'sprefix_count.Normalize strings safely with an anchored regex
Both
insertandcount_with_prefixmust call one shared_normalizehelper so queries like"v2node99"transform identically (-> "v2node") to stored words like"v2Node9"(-> "v2node").When building the regular expression for
strip_trailing_digits, two details keep behavior exact and linear-time: 1. Anchor with\Zrather than$: In Python'sremodule,$matches either the end of the string or right before a trailing"\n", so[0-9]+$would mistakenly strip"12"from"abc12\n".\Zmatches strictly at the true end of the string. 2. Guard with(?<![0-9])to preventO(L^2)backtracking: On a string like"111111a", unguarded[0-9]+\Zattempts a match starting at index0, fails at'a', retries at index1, index2, and so on in quadratic time. Adding the negative lookbehind(?<![0-9])("not preceded by a digit") restricts match attempts to the first digit of each contiguous digit block:String: " v 2 2 2 n 4 9 " Index: 0 1 2 3 4 5 6 (?<![0-9]): ^ ^ <-- regex tries only index 1 and index 5 Match \Z?: no YES -> deletes "49", yielding "v222n"import re TRAILING_DIGITS = re.compile(r"(?<![0-9])[0-9]+\Z")And inside
PrefixCounter:def _normalize(self, text: str) -> str: """Apply identical normalization rules to both stored words and query prefixes.""" # Phase 1: fold uppercase letters to lowercase when case-insensitive matching is enabled if self.case_insensitive: text = text.lower() # Phase 2: strip only the final contiguous block of digits when trailing-digit removal is enabled if self.strip_trailing_digits: text = TRAILING_DIGITS.sub("", text) return textBuild `TrieNode`, `PrefixCounter`, and batch replay
Each
TrieNodestores achildrendictionary mapping characters to child nodes andprefix_count = 0. Notice thatinsertincrementsself.root.prefix_countbefore looping over characters socount_with_prefix("")counts every inserted string (including""):class TrieNode: def __init__(self): # children: dict mapping a single character -> child TrieNode, e.g. {'s': TrieNode(), 'v': TrieNode()} self.children: Dict[str, "TrieNode"] = {} # prefix_count: how many inserted words pass through this node (share the prefix up to here) self.prefix_count: int = 0 class PrefixCounter: def __init__(self, case_insensitive: bool = False, strip_trailing_digits: bool = False): # root represents the empty prefix "" before consuming any characters self.root = TrieNode() self.case_insensitive = case_insensitive self.strip_trailing_digits = strip_trailing_digits def _normalize(self, text: str) -> str: """Apply identical normalization rules to both stored words and query prefixes.""" if self.case_insensitive: text = text.lower() if self.strip_trailing_digits: text = TRAILING_DIGITS.sub("", text) return text def insert(self, word: str) -> None: normalized_word = self._normalize(word) node = self.root node.prefix_count += 1 for ch in normalized_word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.prefix_count += 1 def count_with_prefix(self, prefix: str) -> int: normalized_prefix = self._normalize(prefix) node = self.root for ch in normalized_prefix: if ch not in node.children: return 0 node = node.children[ch] return node.prefix_countThen
prefix_searchreplayszip(operations, arguments)and collectsNoneor the integer match count for each command.Trace Example 1 step by step
Trace the 6 commands in Example 1 (
case_insensitive=False,strip_trailing_digits=False), writingchar:prefix_countat each trie node:1. insert("spark") trie: root:1 -> s:1 -> p:1 -> a:1 -> r:1 -> k:1 results: [None] 2. insert("spa") trie: root:2 -> s:2 -> p:2 -> a:2 -> r:1 -> k:1 results: [None, None] 3. count_with_prefix("spa") walk: root -> s -> p -> a (prefix_count == 2) results: [None, None, 2] 4. insert("space") trie: root:3 -> s:3 -> p:3 -> a:3 -> r:1 -> k:1 └-> c:1 -> e:1 results: [None, None, 2, None] 5. count_with_prefix("sp") walk: root -> s -> p (prefix_count == 3) results: [None, None, 2, None, 3] 6. count_with_prefix("sparkle") walk: root -> s -> p -> a -> r -> k -> 'l' missing -> 0 results: [None, None, 2, None, 3, 0]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import re # Match a run of ASCII digits right at the true end of the string: # - \Z matches only the very end of the string (unlike $, which also matches before a final "\n"). # - (?<![0-9]) is a negative lookbehind requiring the match to start at the first digit of a run, # which prevents O(L^2) regex backtracking when a long digit run appears mid-string (e.g. "111...1a"). TRAILING_DIGITS = re.compile(r"(?<![0-9])[0-9]+\Z") class TrieNode: def __init__(self): # children: dict mapping a single character -> child TrieNode, e.g. {'s': TrieNode(), 'v': TrieNode()} self.children: Dict[str, "TrieNode"] = {} # prefix_count: how many inserted words pass through this node (share the prefix up to here) self.prefix_count: int = 0 class PrefixCounter: def __init__(self, case_insensitive: bool = False, strip_trailing_digits: bool = False): # root represents the empty prefix "" before consuming any characters self.root = TrieNode() self.case_insensitive = case_insensitive self.strip_trailing_digits = strip_trailing_digits def _normalize(self, text: str) -> str: """Apply identical normalization rules to both stored words and query prefixes.""" # Phase 1: fold uppercase letters to lowercase when case-insensitive matching is enabled if self.case_insensitive: text = text.lower() # Phase 2: strip only the final contiguous block of digits when trailing-digit removal is enabled if self.strip_trailing_digits: text = TRAILING_DIGITS.sub("", text) return text def insert(self, word: str) -> None: normalized_word = self._normalize(word) node = self.root # Every inserted word (including "") starts with the empty prefix, so increment root first node.prefix_count += 1 # Walk character by character, creating missing branches and incrementing each prefix along the path for ch in normalized_word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.prefix_count += 1 def count_with_prefix(self, prefix: str) -> int: normalized_prefix = self._normalize(prefix) node = self.root # Follow the normalized prefix characters down the trie; falling off means zero words match for ch in normalized_prefix: if ch not in node.children: return 0 node = node.children[ch] # Every word that starts with normalized_prefix passed through `node` during insert() return node.prefix_count def prefix_search(operations: List[str], arguments: List[List[str]], case_insensitive: bool = False, strip_trailing_digits: bool = False) -> List[Optional[int]]: counter = PrefixCounter(case_insensitive, strip_trailing_digits) # results: one entry per operation (None for "insert", integer match count for "count_with_prefix") results: List[Optional[int]] = [] # zip stops at len(operations), safely ignoring any extra trailing items in `arguments` for op, args in zip(operations, arguments): arg_text = args[0] if op == "insert": counter.insert(arg_text) results.append(None) elif op == "count_with_prefix": match_count = counter.count_with_prefix(arg_text) results.append(match_count) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of a trie (a tree structure that stores strings one character per branch from the root) as a nested hallway of labeled doors with a tally clicker mounted on every door. Door 's' leads to 'sp', which leads to 'spa', and so on. Each time we insert a word, we walk through the doors spelling that word and click every visited door's counter up by 1; later, to find how many stored words start with "spa", we walk straight to the 'spa' door and read its counter without inspecting any rooms further down the hall.
Keeping normalized words in a flat list and checking word.startswith(prefix) on every query takes O(W * P) time for W stored words and prefix length P, forcing thousands of words sharing "sp" to be re-scanned character by character on each query. Even a trie that records counts only at word endings would have to traverse the entire subtree below "spa" at query time to sum up finished words.
Walk through Example 2's idea with case_insensitive=True and strip_trailing_digits=True (using a regular expression—a pattern specification for matching character sequences—to trim digits at the end of a string):
insert("Sensor42"): normalization lowercases and removes"42", producing"sensor". Walkingroot -> s -> e -> n -> s -> o -> rsetsprefix_count = 1along that chain.insert("SENSOR007"): normalization also yields"sensor", bumpingprefix_countto2alongroot -> s -> e -> n -> s -> o -> r.count_with_prefix("Sens99"): normalization yields"sens". Walkingroot -> s -> e -> n -> slands on's', whoseprefix_countis2, returning2immediately.
Complexity
Let L be the length of the input string in one operation, N be the total length of all normalized words inserted, and Q be len(operations).
- Time: O(L) per operation (and
O(sum of L)across allQoperations). Lowercasing scans theLcharacters once, our anchored regex with a negative lookbehind (a zero-width assertion checking that the preceding character is not a digit without consuming it) tests only the start of each digit run inO(L)time, and traversing the trie performs oneO(1)average dictionary lookup per character regardless of collection size. - Space: O(N) auxiliary memory for the trie (plus
O(Q)for the output list). In the worst case where inserted words share no prefixes, each character allocates oneTrieNode; shared prefixes reuse nodes and consume less space.
Edge cases
- Empty prefix
"": Every string starts with"", socount_with_prefix("")remains atself.rootand returns the total count of inserted words (0when empty). - Empty word
""or all-digit word ("2026"withstrip_trailing_digits=True): Normalizes to"", incrementing onlyself.root.prefix_count; matched by""and by no non-empty prefix. - Duplicate words: Inserting
"go"twice incrementsroot -> g -> otwice, behaving as a multiset (a collection where duplicate insertions are kept and counted separately). - Prefix longer than stored words (
"sparkle"when only"spark"exists): Steps off the end of the branch and immediately returns0. - Interior digits (
"v2Node9"): Only the final digit block"9"touches\Z, preserving'2'inside"v2node". - Trailing newline after digits (
"abc12\n"): Because"\n"follows"12",\Zleaves the string untouched as"abc12\n", whereas$in Python would mistakenly strip"12"before"\n". - Long interior digit run (
"1" * 16000 + "a"):(?<![0-9])[0-9]+\Zattempts a match only at index0inO(L)time instead of retrying from every'1'inO(L^2)time. - Extra trailing entries in
arguments: Pairing withzip(operations, arguments)stops cleanly once alllen(operations)commands have run.
Common mistakes
- Normalizing on
insertbut forgetting to normalize oncount_with_prefix: Causes queries like"v2node99"or"Sensor"to miss normalized entries stored as"v2node"or"sensor". - Tracking only word-end flags instead of pass-through counts: A boolean
is_endflag reports only exact matches for"spa"(1in Example 1), missing"spark"and"space". - Skipping
self.root.prefix_count += 1: Leavescount_with_prefix("")stuck at0. - Stripping all digits (
re.sub(r"[0-9]+", "", text)): Deletes interior digits too, corrupting"v2Node9"into"vNode". - Looping over
argumentsdirectly instead ofzip(operations, arguments): RaisesIndexErrororTypeErrorwhenargumentscarries extra trailing items.
Alternative approaches
- Prefix frequency hash map: On
insert(word), incrementcounts[word[:k]]in a hash map (key-value table withO(1)average lookup) for every slicek = 0..L. Queries takeO(L)time to hash the prefix, at the cost ofO(L^2)slicing work and memory per insertion. - Sorted word array + binary search: For static workloads where all insertions precede all queries, sorting normalized words once (
O(W * L log W)) places all matches forprefixcontiguously sobisectcounts them inO(L log W)time with minimal memory overhead. text.rstrip("0123456789"): When a regular expression is not explicitly required, Python'sstr.rstripstrips trailing ASCII digits cleanly inO(L)time.
Follow-up questions
- How would you implement a companion routine that deletes every node matching a target integer from a singly linked list in O(1) extra space? Attach a dummy node (a temporary sentinel node placed ahead of
headso removing the first node needs no special case) and walk a singleprevpointer forward. Wheneverprev.next.val == target, unlink that node viaprev.next = prev.next.nextwithout advancingprevso back-to-back matching nodes are checked too; otherwise setprev = prev.next. Every node is visited once inO(n)time andO(1)auxiliary space.
text
Delete target = 4 from [4 -> 4 -> 9]:
dummy -> [4] -> [4] -> [9] -> None
^prev bypass first 4 (keep prev at dummy!)
dummy --------> [4] -> [9] -> None
^prev bypass second 4 (keep prev at dummy!)
dummy ---------------> [9] -> None (return dummy.next)
```python class ListNode: def init(self, val: int = 0, next: "ListNode | None" = None): self.val = val self.next = next
def delete_target_nodes(head: "ListNode | None", target: int) -> "ListNode | None": dummy = ListNode(0, head) prev = dummy while prev.next is not None: if prev.next.val == target: prev.next = prev.next.next # re-check new prev.next before advancing else: prev = prev.next return dummy.next ```
-
How could you add a remove(word) operation to the trie without breaking prefix counts for other stored words? Add an
end_count: int = 0counter toTrieNodethat increments only at the terminal node ofinsert(word), allowingremove(word)to verify first thatwordwas actually inserted as a whole word (so attempting to remove"spa"when only"spark"is stored returnsFalsewithout corrupting"spark"'s prefix counts). Once confirmed, decrementend_counton that terminal node, walk the normalized path fromself.rootsubtracting1from each node'sprefix_count, and prune any child entry fromnode.childrenwhoseprefix_countreaches0to reclaim memory inO(L)time. -
Where does str.lower() fall short for international text, and how should Unicode case-insensitive prefix matching be handled? Standard
.lower()handles ASCII and common Latin letters, but misses multi-character and locale-independent mappings such as German'ß'matching"SS"; replace it withstr.casefold(), which performs Unicode case folding (mapping characters into a canonical caseless form such as'ß' -> "ss"so"STRASSE"matches prefix"straß"). Combineunicodedata.normalize("NFC", text)beforehand so composed accented characters (like'é') and decomposed sequences ('e'+ combining acute accent) produce identical code-point paths in the trie.
Follow-up questions
- How would you implement a companion routine that deletes every node matching a target integer from a singly linked list in O(1) extra space?
- How could you add a remove(word) operation to the trie without breaking prefix counts for other stored words?
- Where does str.lower() fall short for international text, and how should Unicode case-insensitive prefix matching be handled?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array