- 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
- 61 lines of C++ from the credited upstream file 3034.cpp.
- The implementation visibly relies on sequence storage.
- 4 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.
1class Solution {2 public:3 int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {4 const vector<int> numsPattern = getNumsPattern(nums);5 return kmp(numsPattern, pattern);6 }7 8 private:9 int getNum(int a, int b) {10 if (a < b)11 return 1;12 if (a > b)13 return -1;14 return 0;15 }16 17 vector<int> getNumsPattern(const vector<int>& nums) {18 vector<int> numsPattern;19 for (int i = 1; i < nums.size(); ++i)20 numsPattern.push_back(getNum(nums[i - 1], nums[i]));21 return numsPattern;22 }23 24 25 int kmp(const vector<int>& nums, const vector<int>& pattern) {26 const vector<int> lps = getLPS(pattern);27 int res = 0;28 int i = 0; 29 int j = 0; 30 while (i < nums.size()) {31 if (nums[i] == pattern[j]) {32 ++i;33 ++j;34 if (j == pattern.size()) {35 ++res;36 j = lps[j - 1];37 }38 } else if (j > 0) { 39 40 j = lps[j - 1];41 } else {42 ++i;43 }44 }45 return res;46 }47 48 49 50 vector<int> getLPS(const vector<int>& pattern) {51 vector<int> lps(pattern.size());52 for (int i = 1, j = 0; i < pattern.size(); ++i) {53 while (j > 0 && pattern[j] != pattern[i])54 j = lps[j - 1];55 if (pattern[i] == pattern[j])56 lps[i] = ++j;57 }58 return lps;59 }60};61