Detect Pattern of Length M Repeated K or More Times - Problem

Imagine you're analyzing data streams and need to identify repeating patterns to detect anomalies or trends. Given an array of positive integers arr, your task is to find if there exists a pattern of length m that repeats k or more times consecutively.

A pattern is a contiguous subarray that appears multiple times back-to-back without any gaps or overlaps. For example, in the array [1,2,4,4,4,4], the pattern [4] of length 1 repeats 4 times consecutively.

Goal: Return true if such a pattern exists, false otherwise.

Key Points:

  • Patterns must be consecutive (no gaps between repetitions)
  • Patterns cannot overlap with themselves
  • You need at least k repetitions of the pattern

Input & Output

example_1.py โ€” Basic Pattern
$ Input: arr = [1,2,4,4,4,4], m = 1, k = 3
โ€บ Output: true
๐Ÿ’ก Note: The pattern [4] of length 1 repeats 4 times consecutively, which is โ‰ฅ 3 times required.
example_2.py โ€” Multi-element Pattern
$ Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
โ€บ Output: true
๐Ÿ’ก Note: The pattern [1,2] of length 2 repeats exactly 2 times consecutively at the beginning.
example_3.py โ€” No Valid Pattern
$ Input: arr = [1,2,3,1,2], m = 2, k = 3
โ€บ Output: false
๐Ÿ’ก Note: No pattern of length 2 can repeat 3 times in an array of only 5 elements (would need 6+ elements).

Visualization

Tap to expand
Pattern Detection: [1,2,4,4,4,4]124444Pattern [4] repeats 4 timesm=1, k=3 satisfiedโœ“ Pattern Found: Return True
Understanding the Visualization
1
Identify candidate position
Start checking from each valid position in the array
2
Verify pattern repetition
Use modular arithmetic to check if elements repeat every m positions
3
Count consecutive matches
If we get mร—k matches, we found a valid pattern
Key Takeaway
๐ŸŽฏ Key Insight: Instead of creating and comparing subarrays, we can efficiently verify pattern repetitions by checking if elements at distance m apart are equal throughout the sequence.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n * m * k)

We iterate through n positions and for each position check up to m*k elements

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for counters and indices

n
2n
โœ“ Linear Space

Constraints

  • 2 โ‰ค arr.length โ‰ค 100
  • 1 โ‰ค arr[i] โ‰ค 100
  • 1 โ‰ค m โ‰ค 100
  • 2 โ‰ค k โ‰ค 100
  • Key constraint: arr.length โ‰ฅ m ร— k (otherwise impossible)
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
28.5K Views
Medium Frequency
~15 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen