Blind 75
36 / 75Free practice

Implement Trie (Prefix Tree)

Medium · Tries

Jump to code

Implement insert(word), search(word), and startsWith(prefix) for lowercase words. Search requires a whole stored word; startsWith only requires a matching prefix.

Examples

Example 1

operations = ["insert","search","search","startsWith","insert","search"]
words = ["apple","apple","app","app","app","app"]

Output: [true,false,true,true]

Example 2

operations = ["insert","search","startsWith"]
words = ["hello","hello","he"]

Output: [true,true]

Constraints

  • 1 <= word.length, prefix.length <= 1000
  • word and prefix are made up of lowercase English letters.

Function contract

Implement Trie with insert(word), search(word), and startsWith(prefix). Each case starts a new Trie. The grader returns only the boolean results of search and startsWith; insert has no output.

Need a hint?

A path and a complete word are different states.

Asked in real interviews

Candidates reported versions of Implement Trie (Prefix Tree) from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    "insert",
    "search",
    "search",
    "startsWith",
    "insert",
    "search"
  ],
  [
    "apple",
    "apple",
    "app",
    "app",
    "app",
    "app"
  ]
]
Expected
[
  true,
  false,
  true,
  true
]
Case 2
Input
[
  [
    "insert",
    "search",
    "startsWith"
  ],
  [
    "hello",
    "hello",
    "he"
  ]
]
Expected
[
  true,
  true
]
Case 3
Input
[
  [
    "search",
    "startsWith"
  ],
  [
    "a",
    "a"
  ]
]
Expected
[
  false,
  false
]
Case 4
Input
[
  [
    "insert",
    "insert",
    "search",
    "startsWith"
  ],
  [
    "app",
    "apple",
    "app",
    "apple"
  ]
]
Expected
[
  true,
  true
]
Case 5
Input
[
  [
    "insert",
    "search",
    "startsWith",
    "search"
  ],
  [
    "dog",
    "do",
    "do",
    "dog"
  ]
]
Expected
[
  false,
  true,
  true
]

Drafts are saved per language in this browser when storage is available.