-
Notifications
You must be signed in to change notification settings - Fork 3
/
Detect Pattern of Length M Repeated K or More Times
68 lines (48 loc) · 2.57 KB
/
Detect Pattern of Length M Repeated K or More Times
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Problem Statement:
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.
Solution:
class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
### O(nk); O(n)
# initialize dict which will keep track of patterns
patterns=defaultdict(int)
# set left and right pointer
left=0
right=m
while right<=len(arr):
# if current pattern is previously visited and is consecutive to current pattern
if tuple(arr[left:right]+[left-1]) in patterns:
# update end index of current pattern and increment count
patterns[tuple(arr[left:right]+[right-1])]=patterns[tuple(arr[left:right]+[left-1])]+1
# check if cnt is greater or equal to k
if patterns[tuple(arr[left:right]+[right-1])]>=k:
return True
else:
# set current pattern as visited with its ending index
patterns[tuple(arr[left:right]+[right-1])]=1
# increment left and right pointers
left+=1
right+=1
return False