Detect Pattern of Length M Repeated K or More Times
This problem can be solved using a sliding window approach.
Python solution:
|
|
This works as follows:
The function
containsPattern
takes four parameters:arr
(the input array),m
(the pattern length),k
(the minimum number of repetitions), and returns a boolean indicating whether there exists a pattern of lengthm
that is repeatedk
or more times.The main part of the function is a loop that iterates over the array
arr
from the beginning ton - m * k + 1
, wheren
is the length of the array. This is because we need to check patterns of lengthm * k
, and this is the last starting point that leaves enough elements for such a pattern.For each
i
, it checks if the subarray ofarr
starting fromi
with lengthm * k
(arr[i:i + m * k]
) is the same as the subarray ofarr
starting fromi
with lengthm
(arr[i:i + m]
) repeatedk
times. This is done using the==
operator, which in Python compares the contents of the lists, not just their references.If the condition is true for any
i
, it returnsTrue
. If it never finds a match, it returnsFalse
after the loop ends.This works because any valid pattern of length
m
that is repeatedk
or more times will be a subarray ofarr
of lengthm * k
.
Readable Solution
|
|
This function checks if there is a pattern of length m
that is repeated k
or more times in the input array arr
. The idea behind the solution is to scan the array, comparing each element with the element m
positions ahead. Let’s break down how it works:
Initialize a counter
cnt
to 0. This counter keeps track of how many consecutive repetitions of a pattern of lengthm
we’ve seen so far.Loop through the elements in
arr
up to the indexlen(arr) - m
. We stopm
places before the end because we’re always comparing with the elementm
places ahead.If the current element
arr[i]
is not equal to the elementm
places aheadarr[i + m]
, then the current pattern has been broken. Resetcnt
to 0.If
arr[i]
is equal toarr[i + m]
, incrementcnt
. This line is equivalent to:1 2
if arr[i] == arr[i + m]: cnt += 1
If
cnt
reaches(k - 1) * m
, returnTrue
. The reason why it’s(k - 1) * m
instead ofk * m
is because we’re counting additional matches beyond the first one. In other words, whencnt == m
, we’ve foundk
repetitions of a pattern of lengthm
.If we finish the loop without having returned
True
, returnFalse
. This means no qualifying pattern has been found inarr
.
The function will return True
as soon as it finds a pattern of length m
that repeats k
or more times, or False
if no such pattern exists.