#1032

Stream of Characters

Hard
ArrayStringDesignTrieData StreamTrieDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a Trie allows us to efficiently check for suffixes by traversing the Trie in reverse. This is much faster than checking every suffix individually.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build a Trie from the reversed words list.
  2. 2Step 2: For each character added to the stream, append it to the front of a stream string.
  3. 3Step 3: Traverse the Trie using the characters from the stream, checking if we reach a terminal node (indicating a match).
  4. 4Step 4: If we reach a terminal node during traversal, return true; otherwise, return false.
solution.py28 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_end = False
5
6class StreamChecker:
7    def __init__(self, words):
8        self.trie = TrieNode()
9        for word in words:
10            node = self.trie
11            for char in reversed(word):
12                if char not in node.children:
13                    node.children[char] = TrieNode()
14                node = node.children[char]
15            node.is_end = True
16        self.stream = ''
17
18    def query(self, letter):
19        self.stream = letter + self.stream
20        node = self.trie
21        for char in self.stream:
22            if char in node.children:
23                node = node.children[char]
24                if node.is_end:
25                    return True
26            else:
27                break
28        return False

Complexity note: The time complexity is O(n) because each query processes the character and traverses the Trie, which is efficient due to the structure of the Trie. The space complexity is O(n) due to storing the Trie nodes.

  • 1Using a Trie allows for efficient suffix checking by leveraging character-based traversal.
  • 2Reversing the words when inserting into the Trie enables direct suffix matching.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.