Implement Trie (Prefix Tree)

Implement trieQuery

A trie (prefix tree) stores a set of words so that both exact-word lookup and prefix lookup are fast, no matter how many words share the same start. Given a list of words to insert and a single query string, answer one of two questions depending on isPrefixQuery: does query match a complete inserted word exactly, or does query match at least the start of some inserted word? Every node in the trie represents one character position; a path from the root spells out a prefix, and a node flagged as an "end" marks a spot where some inserted word actually finishes. Two words that share a prefix — like "app" and "apple" — share the same nodes along that shared path, splitting apart only where their letters first differ. Walking a query one character at a time either falls off the trie immediately (no inserted word can satisfy it) or lands on a real node — whether that counts as a match just depends on whether the query needs to be a complete word or merely a prefix.

Example 1:

Input: words = ["apple"], query = "apple", isPrefixQuery = false

Output: true

Example 2:

Input: words = ["apple"], query = "app", isPrefixQuery = false

Output: false

Example 3:

Input: words = ["apple"], query = "app", isPrefixQuery = true

Output: true

+ 10 hidden test cases run on Submit.

Constraints:

  • 0 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 30
  • 0 ≤ query.length ≤ 30
  • words[i] and query consist of lowercase English letters

words =

["apple"]

query =

apple

isPrefixQuery =

false