Given an array of positive integers arr
, find a pattern of length m
that is repeated at least k
times in the array. The pattern must be consecutive, which means that between consecutive appearances of the same pattern, there cannot be any other elements.
m
and k
?arr
be empty or have very few elements?Let’s assume:
m
and k
is 1.m
repeated at least k
times consecutively.def contains_pattern(arr, m, k):
n = len(arr)
for i in range(n - m * k + 1):
pattern = arr[i:i + m]
matches = 0
for j in range(i, n - m + 1, m):
if arr[j:j + m] == pattern:
matches += 1
else:
break
if matches == k:
return True
return False
n
. Iterate over the array, checking for potential patterns starting at each index i
.i
, define a sub-array of length m
as the pattern.i
, stepping by m
to check the next segment of length m
.k
, return True
.k
and the consecutive checking breaks, continue to the next starting index until all possibilities are exhausted.m
is found k
or more times consecutively, return False
.n
is the length of the array. In the worst case, every possible start index could be checked, each time comparing up to m
elements k
times.
Thus, the complexity is approximately (O(n \cdot m)).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?