Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check pattern of length m repeated K or more times exists or not in Python
Suppose we have an array nums with positive values, we have to find a pattern of length m that is repeated k or more times. Here a pattern is a non-overlapping subarray (consecutive) that consists of one or more values and are repeated multiple times. A pattern is defined by its length and number of repetitions. We have to check whether there exists a pattern of length m that is repeated k or more times or not.
So, if the input is like nums = [3,5,1,4,3,1,4,3,1,4,3,9,6,1], m = 3, k = 2, then the output will be True because there is a pattern [1,4,3] which is present 3 times.
Algorithm
To solve this, we will follow these steps ?
-
For each starting position
iin the array:Extract a subarray
sub1of lengthm*kstarting from indexiCreate
sub2by repeating the firstmelementsktimesIf
sub1equalssub2, returnTrue
If no pattern is found, return
False
Implementation
Let us see the following implementation to get better understanding ?
def solve(nums, m, k):
for i in range(len(nums) - m*k + 1):
sub1 = nums[i:i+m*k]
sub2 = nums[i:i+m] * k
if sub1 == sub2:
return True
return False
nums = [3, 5, 1, 4, 3, 1, 4, 3, 1, 4, 3, 9, 6, 1]
m = 3
k = 2
print(solve(nums, m, k))
The output of the above code is ?
True
How It Works
In this example:
At index 2: pattern
[1, 4, 3]repeats 3 times consecutivelysub1 = [1, 4, 3, 1, 4, 3](6 elements from index 2)sub2 = [1, 4, 3] * 2 = [1, 4, 3, 1, 4, 3]Since
sub1 == sub2, the function returnsTrue
Edge Case Example
Let's test with a case where no pattern exists ?
def solve(nums, m, k):
for i in range(len(nums) - m*k + 1):
sub1 = nums[i:i+m*k]
sub2 = nums[i:i+m] * k
if sub1 == sub2:
return True
return False
nums = [1, 2, 3, 4, 5, 6]
m = 2
k = 2
print(solve(nums, m, k))
The output of the above code is ?
False
Conclusion
This algorithm efficiently checks for repeated patterns by comparing subarrays with their expected repeated forms. The time complexity is O(n*m*k) where n is the array length, making it suitable for moderate-sized inputs.
