Python coding

Word counts by prefix

Write a class PrefixCounter that keeps a collection of words in which the same word can be stored several times.

  • add(word) stores one more copy of word.
  • remove(word) deletes one copy of word; if no copy is stored, it does nothing.
  • count(word) returns how many copies of exactly word are stored.
  • count_prefix(prefix) returns how many stored words, copies included, start with prefix; a word equal to prefix counts.

Words and prefixes use lowercase a–z and have 1 to 20 letters. Each operation should cost O(length of its argument), however many words are stored.

The tests call the provided run_counter(ops): it applies each operation in order and returns the list of results (None for add and remove, shown as null).

Besides the tests, one large input (15,000 operations) with a ~600 ms limit (scaled to your device's speed): brute force won't pass.

  • run_counter([["add","note"],["add","note"],["add","notes"],["count","note"],["count_prefix","not"],["remove","note"],["count","note"],["count_prefix","no"]]) → [null,null,null,2,3,null,1,2]
  • run_counter([["count","a"],["count_prefix","a"],["remove","a"],["add","a"],["count_prefix","a"],["count","a"]]) → [0,0,null,null,1,1]
  • run_counter([["add","car"],["count_prefix","cart"],["count_prefix","car"],["count","ca"],["count_prefix","c"],["add","cart"],["count_prefix","car"]]) → [null,0,1,0,1,null,2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Use a trie, but store numbers instead of flags: each node keeps how many stored words pass through it and how many end exactly there.

Hint 2

add adds 1 to the pass count of every node on the word's path and 1 to the end count of its last node; count_prefix reads the pass count where the prefix ends.

Hint 3

remove is add with -1, but only when count(word) > 0: a word that is only the beginning of a stored one ("car" when just "card" is stored) has a path but no copies.

Solution and why it works
pythonO(L) per operation, L = length of its argument · O(total letters added)
# --- your code ---
class PrefixCounter:
    def __init__(self) -> None:
        self.root = {}                   # node = {letter: child, "#": words through it, "$": words ending at it}

    def _walk(self, s: str) -> dict:
        node = self.root
        for ch in s:
            node = node.get(ch, {})      # a missing branch acts as an empty node
        return node

    def add(self, word: str, step: int = 1) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
            node["#"] = node.get("#", 0) + step     # one more (or less) word passes here
        node["$"] = node.get("$", 0) + step

    def remove(self, word: str) -> None:
        if self.count(word) > 0:         # an absent word must change nothing, even if its path exists
            self.add(word, -1)

    def count(self, word: str) -> int:
        return self._walk(word).get("$", 0)

    def count_prefix(self, prefix: str) -> int:
        return self._walk(prefix).get("#", 0)


# --- provided: do not edit ---
def run_counter(ops: list[list]) -> list:
    counter = PrefixCounter()
    return [getattr(counter, name)(*args) for name, *args in ops]

Each node counts the words whose path crosses it, so the answer to count_prefix is already waiting at the prefix's last node: one walk of O(length), with no scan of the words below it. add and remove keep the counts right by touching only the word's own path. The trap is remove on an absent word: its path may exist because a longer word shares it, and decrementing anyway throws the counts off, even below zero.