Stream of Characters

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

Design a StreamChecker class that initializes with a list of words and provides a query method.

For each call to query(letter), the method should return true if any suffix of the characters queried so far (including the current character) matches any word in the given list.

Implement the class using a trie built from the reversed words, so that each query checks suffixes efficiently.

Examples

Example 1:

Input: operations = ["StreamChecker","query","query","query","query","query","query","query","query","query","query","query","query"], operands = [[["cd","f","kl"]],["a"],["b"],["c"],["d"],["e"],["f"],["g"],["h"],["i"],["j"],["k"],["l"]]

Output: [null,false,false,false,true,false,true,false,false,false,false,false,true]

Explanation: After querying "c" then "d", the suffix "cd" matches. After querying "f", the suffix "f" matches. After querying "k" then "l", the suffix "kl" matches.

Example 2:

Input: operations = ["StreamChecker","query","query","query","query","query","query"], operands = [[["ab","ba","aaab","abab","baa"]],["a"],["a"],["a"],["a"],["b"],["a"]]

Output: [null,false,false,false,false,true,true]

Explanation: After querying "a","a","a","a","b", the suffixes "ab" and "aaab" match. After querying "a", the suffix "ba" matches.

Constraints

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 200
  • words[i] consists of lowercase English letters
  • letter is a lowercase English letter
  • At most 4 * 10⁴ calls will be made to query
Source: Trie pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle