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": Inserts arguments[i][0] into the collection and appends None to the returned list. Duplicate insertions are retained and counted separately.
  • "count_with_prefix": Counts how many strings inserted so far begin with the prefix arguments[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:

  1. case_insensitive: When True, convert letters to lowercase (text.lower()) so uppercase and lowercase variants match identically.
  2. strip_trailing_digits: When True, 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^4
  • len(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 item arguments[i][0] is a string.
  • The sum of len(arguments[i][0]) across all commands is at most 2 * 10^5.

Step-by-step walkthrough

  1. Understand the operations and normalization rules

    We are building a batch prefix counter supporting two commands passed via parallel lists operations and arguments:

    • "insert": adds arguments[i][0] to our collection and appends None to the output list.
    • "count_with_prefix": counts how many previously added strings begin with arguments[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. - arguments may contain extra trailing entries past len(operations), so pairing the two lists with zip(operations, arguments) stops cleanly at len(operations).

  2. 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 calling word.startswith(prefix) on every "count_with_prefix" query.

    Although insertion is O(1), each query inspects all W stored words and compares up to P characters per word (O(W * P) time). With 20,000 insertions followed by 20,000 queries, that executes 400,000,000 string checks — repeatedly re-comparing shared prefixes like "sp" across "spa", "spark", and "space" on every single query.

  3. 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 integer prefix_count directly 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 L of the single string being processed: - On insert(word), increment root.prefix_count and step character by character, creating missing child nodes and adding 1 to each visited node's prefix_count. - On count_with_prefix(prefix), step down the characters of prefix; if any edge is missing return 0, otherwise return the final node's prefix_count.

  4. Normalize strings safely with an anchored regex

    Both insert and count_with_prefix must call one shared _normalize helper 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 \Z rather than $: In Python's re module, $ matches either the end of the string or right before a trailing "\n", so [0-9]+$ would mistakenly strip "12" from "abc12\n". \Z matches strictly at the true end of the string. 2. Guard with (?<![0-9]) to prevent O(L^2) backtracking: On a string like "111111a", unguarded [0-9]+\Z attempts a match starting at index 0, fails at 'a', retries at index 1, index 2, 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 text
    
  5. Build `TrieNode`, `PrefixCounter`, and batch replay

    Each TrieNode stores a children dictionary mapping characters to child nodes and prefix_count = 0. Notice that insert increments self.root.prefix_count before looping over characters so count_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_count
    

    Then prefix_search replays zip(operations, arguments) and collects None or the integer match count for each command.

  6. Trace Example 1 step by step

    Trace the 6 commands in Example 1 (case_insensitive=False, strip_trailing_digits=False), writing char:prefix_count at 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]
    
  7. 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):

  1. insert("Sensor42"): normalization lowercases and removes "42", producing "sensor". Walking root -> s -> e -> n -> s -> o -> r sets prefix_count = 1 along that chain.
  2. insert("SENSOR007"): normalization also yields "sensor", bumping prefix_count to 2 along root -> s -> e -> n -> s -> o -> r.
  3. count_with_prefix("Sens99"): normalization yields "sens". Walking root -> s -> e -> n -> s lands on 's', whose prefix_count is 2, returning 2 immediately.

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 all Q operations). Lowercasing scans the L characters 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 in O(L) time, and traversing the trie performs one O(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 one TrieNode; shared prefixes reuse nodes and consume less space.

Edge cases

  • Empty prefix "": Every string starts with "", so count_with_prefix("") remains at self.root and returns the total count of inserted words (0 when empty).
  • Empty word "" or all-digit word ("2026" with strip_trailing_digits=True): Normalizes to "", incrementing only self.root.prefix_count; matched by "" and by no non-empty prefix.
  • Duplicate words: Inserting "go" twice increments root -> g -> o twice, 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 returns 0.
  • 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", \Z leaves 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]+\Z attempts a match only at index 0 in O(L) time instead of retrying from every '1' in O(L^2) time.
  • Extra trailing entries in arguments: Pairing with zip(operations, arguments) stops cleanly once all len(operations) commands have run.

Common mistakes

  • Normalizing on insert but forgetting to normalize on count_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_end flag reports only exact matches for "spa" (1 in Example 1), missing "spark" and "space".
  • Skipping self.root.prefix_count += 1: Leaves count_with_prefix("") stuck at 0.
  • Stripping all digits (re.sub(r"[0-9]+", "", text)): Deletes interior digits too, corrupting "v2Node9" into "vNode".
  • Looping over arguments directly instead of zip(operations, arguments): Raises IndexError or TypeError when arguments carries extra trailing items.

Alternative approaches

  • Prefix frequency hash map: On insert(word), increment counts[word[:k]] in a hash map (key-value table with O(1) average lookup) for every slice k = 0..L. Queries take O(L) time to hash the prefix, at the cost of O(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 for prefix contiguously so bisect counts them in O(L log W) time with minimal memory overhead.
  • text.rstrip("0123456789"): When a regular expression is not explicitly required, Python's str.rstrip strips trailing ASCII digits cleanly in O(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 head so removing the first node needs no special case) and walk a single prev pointer forward. Whenever prev.next.val == target, unlink that node via prev.next = prev.next.next without advancing prev so back-to-back matching nodes are checked too; otherwise set prev = prev.next. Every node is visited once in O(n) time and O(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 = 0 counter to TrieNode that increments only at the terminal node of insert(word), allowing remove(word) to verify first that word was actually inserted as a whole word (so attempting to remove "spa" when only "spark" is stored returns False without corrupting "spark"'s prefix counts). Once confirmed, decrement end_count on that terminal node, walk the normalized path from self.root subtracting 1 from each node's prefix_count, and prune any child entry from node.children whose prefix_count reaches 0 to reclaim memory in O(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 with str.casefold(), which performs Unicode case folding (mapping characters into a canonical caseless form such as 'ß' -> "ss" so "STRASSE" matches prefix "straß"). Combine unicodedata.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

Similar questions

More Ansys interview questions

All 1 Ansys questions →