Leetcode 1566. Detect Pattern of Length M Repeated K or More Times
Given an array of positive integers arr
, find a pattern of length m
that is repeated at least k
times. A pattern is a subarray (contiguous subarray) of arr
that:
k
times.m
.Return true
if there exists such a pattern and false
otherwise.
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 times.
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 times.
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) of length 2 is repeated 2 times but not 3 times.
m
?
m
distance from each other.m
or k
be zero or negative?
m
and k
are positive integers.m
times k
to avoid out-of-bound errors.m
starting from each index.m
, check if it repeats k
times consecutively.m
.k
times by comparing the subsequent elements in blocks of size m
.public class DetectPattern {
public boolean containsPattern(int[] arr, int m, int k) {
int n = arr.length;
// Iterate through the array up to length minus (m * (k - 1))
for (int i = 0; i <= n - m * k; i++) {
boolean matchFound = true;
// Check the pattern in chunks of size m
for (int j = 0; j < m * (k - 1); j++) {
if (arr[i + j] != arr[i + j + m]) {
matchFound = false;
break;
}
}
if (matchFound) return true;
}
return false;
}
public static void main(String[] args) {
DetectPattern dp = new DetectPattern();
// Test cases
System.out.println(dp.containsPattern(new int[]{1,2,4,4,4,4}, 1, 3)); // true
System.out.println(dp.containsPattern(new int[]{1,2,1,2,1,1,1,3}, 2, 2)); // true
System.out.println(dp.containsPattern(new int[]{1,2,1,2,1,1,1,3}, 2, 3)); // false
}
}
n - m * k
, checking for patterns. Each pattern check involves comparing up to m * (k - 1)
elements.By adapting this approach, we ensure an efficient and clear solution to the problem.
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?