Detect Pattern of Length M Repeated K or More Times Problem
Description
LeetCode Problem 1566.
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 true if there exists a pattern of length m that is repeated k or more times, otherwise return false.
Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Example 2:
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 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: 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.
Constraints:
2 <= arr.length <= 1001 <= arr[i] <= 1001 <= m <= 1002 <= k <= 100
Solution
Approach: Count Matches One Period Apart
A block of length m repeated k times is a stretch of m * k values where every value equals the one m positions earlier. Counting from the second copy, that means (k - 1) * m indices in a row with arr[i] == arr[i - m].
So scan i from m to the end and keep a counter run:
- If
arr[i] == arr[i - m], add one torun. As soon asrunreaches(k - 1) * m, returntrue. - Otherwise reset
runto0, because a repetition cannot continue across a mismatch.
If the array is shorter than m * k, the answer is false right away. The counter does not care where the pattern starts: any window of (k - 1) * m consecutive matches, plus the m values before it, is exactly k copies of one block.
Complexity: O(n) time and O(1) extra space.
class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
if len(arr) < m * k:
return False
# run: how many indices in a row so far have arr[i] == arr[i - m]
run, need = 0, (k - 1) * m
for i in range(m, len(arr)):
if arr[i] == arr[i - m]:
run += 1
if run == need:
return True
else:
run = 0
return False