Menu
CoddyTech

Implement Trie (Prefix Tree)

MediumTriepython iconjava iconcpp iconc iconjs icon+10

A trie, or prefix tree, stores words so that questions about their beginnings are fast. Build one for lowercase words with three operations: insert w adds the word w, search w tells whether w itself was inserted, and startsWith p tells whether some inserted word begins with p. A word counts as a prefix of itself.

You get the operations in order as ops, and words[i] is the word or prefix for ops[i]. Run them on one trie that starts empty and return one string per operation: "null" for an insert, and "true" or "false" for a search or a startsWith.

Function

trieOps(ops: string-array, words: string-array) → string-array
opsstring-array
the operations, in the order they run
wordsstring-array
the word or prefix for each operation
Returnsstring-array
one answer per operation, as text

Constraints

  • 1 ≤ ops.length ≤ 2000
  • words.length == ops.length
  • Every ops[i] is insert, search or startsWith.
  • 1 ≤ words[i].length ≤ 20
  • words[i] holds only lowercase English letters.

Examples

Input
ops = ["insert", "search", "startsWith", "insert", "search"]words = ["card", "car", "car", "car", "car"]
Output
["null", "false", "true", "null", "true"]
Explanation
Only card is stored at first, so searching for car returns "false": it was never inserted as a word. It is the beginning of card, so startsWith car returns "true". Once car is inserted, the search finds it.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

How would you add a countPrefix p operation that returns how many distinct stored words begin with p, still in O(L) time?

Reset code
def trieOps(ops, words):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

ops = ["insert", "search", "startsWith", "insert", "search"]
words = ["card", "car", "car", "car", "car"]

Expected

["null", "false", "true", "null", "true"]