DSA With AI
Week 10 ยท Tries

Design Add and Search Words Data Structure

Solve Design Add and Search Words Data Structure by recognizing the Tries pattern and turning the prompt into a small invariant before coding.

Medium Tries Week 10 Practice runner

Frame the problem

  • Implement word_dictionary_session with the exact signature used by the interactive runner.
  • Use the visible tests to confirm the input and output shape before reading the final solution.
  • Treat challenge tests as edge-case pressure: empty inputs, repeated values, boundary shapes, or impossible states.
  • State the invariant before code, then dry-run one passing case and one failing-looking case.
1. Reveal example inputs and outputs

Example 1

Input:

word_dictionary_session([
  "addWord",
  "addWord",
  "addWord",
  "search",
  "search",
  "search",
  "search"
], [
  [
    "bad"
  ],
  [
    "dad"
  ],
  [
    "mad"
  ],
  [
    "pad"
  ],
  [
    "bad"
  ],
  [
    ".ad"
  ],
  [
    "b.."
  ]
])

Output:

[
  null,
  null,
  null,
  false,
  true,
  true,
  true
]
2. Brute force first

What direct brute force would be correct for a tiny input? Name the exact repeated work that the target pattern removes.

3. Reveal the insight ladder
  1. Map the prompt to the Tries pattern instead of starting from syntax.
  2. A dot branches to every child at that trie node.
  3. The pattern must consume exactly one trie edge per character.
  4. Only reveal the final code after you can explain why each state update is safe.
4. Dry run before code
  1. word-dict-basic: input [["addWord","addWord","addWord","search","search","search","search"],[["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]] should produce [null,null,null,false,true,true,true]. Hint to check your state: A dot branches to every child at that trie node.
  2. word-dict-length: input [["addWord","search","search"],[["a"],["."],[".."]]] should produce [null,true,false]. Hint to check your state: The pattern must consume exactly one trie edge per character.
5. Reveal final Python solution
def word_dictionary_session(operations: list[str], arguments: list[list[str]]) -> list[Optional[bool]]:
    trie: dict[str, Any] = {}
    output: list[Optional[bool]] = []

    def search(node: dict[str, Any], word: str, index: int) -> bool:
        if index == len(word):
            return "$" in node
        char = word[index]
        if char == ".":
            return any(key != "$" and search(child, word, index + 1) for key, child in node.items())
        return char in node and search(node[char], word, index + 1)

    for op, args in zip(operations, arguments):
        if op == "addWord":
            node = trie
            for char in args[0]:
                node = node.setdefault(char, {})
            node["$"] = True
            output.append(None)
        elif op == "search":
            output.append(search(trie, args[0], 0))
    return output

Complexity: Derive the exact bounds from word_dictionary_session: count how often each input item is visited and the maximum size of the main state structure.

Interview narration

  • I will first describe the invariant in plain language.
  • Then I will explain what data structure carries that invariant across the traversal, loop, recursion, or DP transition.
  • Finally I will walk one edge case before writing the optimized version.

Common traps

  • Solving only the visible example instead of the invariant.
  • Forgetting empty input, singleton input, duplicate values, or impossible-state cases.
  • Revealing the solution before doing a dry run from the starter signature.

Follow-up drills

1. How do you turn this into a timed interview answer?

Start with the invariant, give the brute force in one sentence, name the optimized state, code the core loop or recursion, and run one visible test aloud before mentioning complexity.

2. How do you scale the same pattern to a larger input?

Track which state grows with the input: hash maps and sets grow with distinct values, queues grow with frontier width, recursion grows with depth, heaps grow with active candidates, and DP tables grow with state count.

3. What should you practice from blank tomorrow?

Rewrite word_dictionary_session without looking at the solution, then compare only the invariant and state updates before checking syntax.

Interactive runner

Write the required Python function. Your code runs locally in this browser. Hints reveal one failing case at a time.