Detect Pattern of Length M Repeated K or More Times - Array - Easy - LeetCode
💻 coding

Detect Pattern of Length M Repeated K or More Times - Array - Easy - LeetCode

2 min read 319 words
2 min read
ShareWhatsAppPost on X
  • 1The task is to find a subarray of length m that repeats k or more times consecutively.
  • 2Examples illustrate that patterns must be consecutive and cannot overlap to be valid.
  • 3The solution has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to find a subarray of length m that repeats k or more times consecutively."

Detect Pattern of Length M Repeated K or More Times - Array - Easy - LeetCode

Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.

A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.

Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.

Example 1:

Input: arr = [1,2,4,4,4,4], m = 1, k = 3 Output: true Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less. Example 2:

Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2 Output: true Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times. Example 3:

Input: arr = [1,2,1,2,1,3], m = 2, k = 3 Output: false Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times. Example 4:

Input: arr = [1,2,3,1,2], m = 2, k = 2 Output: false Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count. Example 5:

Input: arr = [2,2,2,2], m = 2, k = 3 Output: false Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.

Constraints:

2 <= arr.length <= 100 1 <= arr[i] <= 100 1 <= m <= 100 2 <= k <= 100

public class Solution {
 public bool ContainsPattern(int[] arr, int m, int k) {
 int count=0;
 for(int i=0;i+m < arr.Length; i++){
 
 if(arr[i]!=arr[i+m]){
 count=0; 
 }
 
 if(arr[i] == arr[i+m]){
 count++;
 }
 
 if(count == (k-1)*m){
 return true;
 } 
 }
 return false;
 }
 
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 27 September 2020 · 2 min read · 319 words

Part of AskGif Blog · coding

You might also like