CodeArchon

mediumTriesGoogleAmazonMicrosoft

Lexicon Lattice

A keyboard autocomplete routine ingests a dictionary and later answers whole-word and prefix lookups in O(length).

Design a prefix tree that supports insert(word), search(word) (exact), and startsWith(prefix).

Choose approach

·
1/7
Narrationstep 1 of 7

Start with just the root sentinel node.

1class Trie:
2 def __init__(self):
3 self.root = {}
4 def insert(self, word):
5 n = self.root
6 for c in word: n = n.setdefault(c, {})
7 n['$'] = True
8 def _walk(self, s):
9 n = self.root
10 for c in s:
11 if c not in n: return None
12 n = n[c]
13 return n
14 def search(self, word):
15 n = self._walk(word); return bool(n and n.get('$'))
16 def startsWith(self, prefix):
17 return self._walk(prefix) is not None
Variables
ops=6

How to think about it

  1. Trie branches off per character — shared prefixes share nodes.
  2. `isEnd` distinguishes search (needs terminator) from startsWith (any node reached).
  3. Every operation is O(length of query).

Edge cases to catch in interview

  • Empty string: root node reached, treat as terminator present.
  • Case sensitivity: assume lowercase a-z unless stated otherwise.

Examples

Example 1[true]
{"ops":[{"op":"insert","word":"car"},{"op":"search","word":"car"}]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed