Menu
CoddyTech

Implement Trie (Prefix Tree)

MediumTriepython iconjava iconcpp iconc iconjs icon+10

Build a trie (prefix tree) 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.

Operation i is ops[i] on words[i]. Run them in order on an empty trie and return one string each: "null" for an insert, "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
car begins card, so startsWith car is "true", but car was never inserted, so the first search is "false". After insert car the search finds it.
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 #1

Test #2

Test #3

Arguments

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

Expected Output

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