Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
Return trueif there exists a pattern of lengthmthat is repeatedkor more times, otherwise returnfalse.
Input: arr =[1,2,4,4,4,4], m =1, k =3Output: trueExplanation: The pattern **(4)** of length 1is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Input: arr =[1,2,1,2,1,1,1,3], m =2, k =2Output: trueExplanation: The pattern **(1,2)** of length 2is repeated 2 consecutive times. Another valid pattern **(2,1)is** also repeated 2 times.
Input: arr =[1,2,1,2,1,3], m =2, k =3Output: falseExplanation: The pattern(1,2)is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
If a pattern of length m is repeated k or more times consecutively, then for any starting index, the subarrays of length m must be equal for k consecutive blocks. We can check for each possible starting index if this is true.
classSolution {
public:bool containsPattern(vector<int>& arr, int m, int k) {
int n = arr.size();
for (int i =0; i <= n - m * k; ++i) {
bool ok = true;
for (int j =0; j < m * k; ++j) {
if (arr[i + j] != arr[i + j % m]) {
ok = false;
break;
}
}
if (ok) return true;
}
return false;
}
};
classSolution {
publicbooleancontainsPattern(int[] arr, int m, int k) {
int n = arr.length;
for (int i = 0; i <= n - m * k; ++i) {
boolean ok =true;
for (int j = 0; j < m * k; ++j) {
if (arr[i + j]!= arr[i + j % m + i]) {
ok =false;
break;
}
}
if (ok) returntrue;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funcontainsPattern(arr: IntArray, m: Int, k: Int): Boolean {
val n = arr.size
for (i in0..n - m * k) {
var ok = truefor (j in0 until m * k) {
if (arr[i + j] != arr[i + j % m]) {
ok = falsebreak }
}
if (ok) returntrue }
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defcontainsPattern(self, arr: list[int], m: int, k: int) -> bool:
n = len(arr)
for i in range(n - m * k +1):
ok =Truefor j in range(m * k):
if arr[i + j] != arr[i + j % m + i]:
ok =Falsebreakif ok:
returnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfncontains_pattern(arr: Vec<i32>, m: i32, k: i32) -> bool {
let n = arr.len() asi32;
for i in0..=n - m * k {
letmut ok =true;
for j in0..m * k {
if arr[(i + j) asusize] != arr[(i + j % m) asusize] {
ok =false;
break;
}
}
if ok {
returntrue;
}
}
false }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
containsPattern(arr: number[], m: number, k: number):boolean {
constn=arr.length;
for (leti=0; i<=n-m*k; ++i) {
letok=true;
for (letj=0; j<m*k; ++j) {
if (arr[i+j] !==arr[i+ (j%m)]) {
ok=false;
break;
}
}
if (ok) returntrue;
}
returnfalse;
}
}