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 i in the array:

    • Extract a subarray sub1 of length m*k starting from index i

    • Create sub2 by repeating the first m elements k times

    • If sub1 equals sub2, return True

  • 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 consecutively

  • sub1 = [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 returns True

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.

Updated on: 2026-03-25T20:20:41+05:30

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements