#1566

Detect Pattern of Length M Repeated K or More Times

Easy
ArrayEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking every possible pattern, we can use a sliding window approach to efficiently count consecutive patterns of length m.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a count variable to track how many times we've seen the current pattern.
  2. 2Step 2: Iterate through the array using a loop, checking for the current pattern starting from each index.
  3. 3Step 3: If the next segment matches the current pattern, increment the count.
  4. 4Step 4: If the count reaches k, return true immediately.
  5. 5Step 5: If no pattern is found after checking all, return false.
solution.py11 lines
1def containsPattern(arr, m, k):
2    n = len(arr)
3    count = 0
4    for i in range(n - m):
5        if arr[i:i + m] == arr[i + m:i + 2 * m]:
6            count += 1
7            if count >= k - 1:
8                return True
9        else:
10            count = 0
11    return False

Complexity note: This approach only requires a single pass through the array, making it O(n) in time complexity.

  • 1Patterns can overlap, so we need to check consecutive segments carefully.
  • 2Using a sliding window can significantly reduce the number of checks needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.