Leetcode 1566. Detect Pattern of Length M Repeated K or More Times
Given an array of positive integers arr, you need to check if there exists a pattern of length m that repeats at least k times consecutively.
Formally, a pattern is a subarray of length m that is repeated k times consecutively without overlapping. More specifically, for an index i, the pattern is arr[i], arr[i+1], ..., arr[i+m-1]. You need to check whether this subarray appears at least k times consecutively such that the overall length of this repeating pattern is m*k.
arr?
m always less than or equal to the length of arr?
k be 1?
k=1, we are looking for any subarray of length m.arr be any positive integer?
true if any such pattern exists is sufficient.To solve this problem, we can implement the following approach:
m*k.m*k positions.m is consecutively repeating k times.#include <vector>
using namespace std;
bool containsPattern(vector<int>& arr, int m, int k) {
int n = arr.size();
for (int i = 0; i <= n - m * k; ++i) {
bool isPattern = true;
for (int j = 0; j < m * k; ++j) {
if (arr[i + j] != arr[i + (j % m)]) {
isPattern = false;
break;
}
}
if (isPattern) {
return true;
}
}
return false;
}
n.m * k makes sense (i <= n - m * k).m * k matches its corresponding element in the repeating pattern.true.false.m*k elements.O(n - m*k) times and the inner loop checks m*k elements.Therefore, the overall complexity is still manageable within the constraints typically given for such problems (assuming n is reasonably large but not excessively so).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?