- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 54 lines of C++ from the credited upstream file 3023.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * Definition for an infinite stream.3 * class InfiniteStream {4 * public:5 * InfiniteStream(vector<int> bits);6 * int next();7 * };8 */9 10class Solution {11 public:12 int findPattern(InfiniteStream* stream, vector<int>& pattern) {13 const vector<int> lps = getLPS(pattern);14 int i = 0; 15 int j = 0; 16 int bit = 0; 17 bool readNext = false;18 while (true) {19 if (!readNext) {20 bit = stream->next();21 readNext = true;22 }23 if (bit == pattern[j]) {24 ++i, readNext = false;25 ++j;26 if (j == pattern.size())27 return i - j;28 }29 30 else if (j > 0) {31 32 j = lps[j - 1];33 } else {34 ++i, readNext = false;35 }36 }37 throw;38 }39 40 private:41 42 43 vector<int> getLPS(const vector<int>& pattern) {44 vector<int> lps(pattern.size());45 for (int i = 1, j = 0; i < pattern.size(); ++i) {46 while (j > 0 && pattern[j] != pattern[i])47 j = lps[j - 1];48 if (pattern[i] == pattern[j])49 lps[i] = ++j;50 }51 return lps;52 }53};54