Approach
Breadth-first search
For Stream of Characters2, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 107 lines of C++ from the credited upstream file stream-of-characters2.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 7 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345678 910111213 14struct AhoNode {15 vector<AhoNode *> children;16 AhoNode *suffix;17 vector<int> outputs;18 AhoNode() :19 children(26, nullptr),20 suffix(nullptr) {}21};22 23class AhoTrie {24public:25 AhoTrie(const vector<string>& patterns) : root_(createACTrie(patterns)) {26 node_ = createACSuffixAndOutputLinks(root_);27 }28 29 vector<int> *step(char letter) {30 while (node_ && !node_->children[letter - 'a']) {31 node_ = node_->suffix;32 }33 node_ = node_ ? node_->children[letter - 'a'] : root_;34 return &node_->outputs; 35 }36 37private:38 AhoNode *createACTrie(const vector<string>& patterns) { 39 auto root = new AhoNode();40 for (int i = 0; i < patterns.size(); ++i) {41 auto node = root;42 for (const auto& c : patterns[i]) {43 if (!node->children[c - 'a']) {44 node->children[c - 'a'] = new AhoNode();45 }46 node = node->children[c - 'a'];47 }48 node->outputs.emplace_back(i);49 }50 return root;51 }52 53 AhoNode *createACSuffixAndOutputLinks(AhoNode *root) { 54 queue<AhoNode *> q;55 for (auto node : root->children) {56 if (!node) {57 continue;58 }59 q.emplace(node);60 node->suffix = root;61 }62 63 while (!q.empty()) {64 auto node = q.front(); q.pop();65 for (int c = 0; c < node->children.size(); ++c) {66 if (!node->children[c]) {67 continue;68 }69 auto child = node->children[c];70 q.emplace(child);71 auto suffix = node->suffix;72 while (suffix && !suffix->children[c]) {73 suffix = suffix->suffix;74 }75 child->suffix = suffix ? suffix->children[c] : root;76 copy(child->suffix->outputs.cbegin(),77 child->suffix->outputs.cend(),78 back_inserter(child->outputs)); 79 }80 }81 82 return root;83 }84 85 AhoNode * const root_;86 AhoNode *node_;87};88 89class StreamChecker {90public:91 StreamChecker(vector<string>& words) : trie_(words) {92 }93 94 bool query(char letter) { 95 return !trie_.step(letter)->empty();96 }97 98private:99 AhoTrie trie_;100};101 102/**103 * Your StreamChecker object will be instantiated and called as such:104 * StreamChecker* obj = new StreamChecker(words);105 * bool param_1 = obj->query(letter);106 */107