8
8
9
9
Subarray = collections .namedtuple ('Subarray' , ('start' , 'end' ))
10
10
11
+ """
12
+ ["a", "b", "c", "b", "a", "d", "c", "a", "e", "a", "a", "b", "e"]
13
+ | | | | | | |
14
+ 1 2 1 2 3 1 3
15
+
16
+ 1 ... 2 ...3 ... 1,2,3 ... 3 ... 2 ... 1
17
+
18
+ """
19
+
20
+ # b...... b c e ......... b
21
+ # first remove l/r characters that aren't in keywords
22
+
23
+ # No keywords, no paragraph, no keywords in paragraph?
24
+ # assume for now none of these can happen
25
+
26
+
27
+ def find_smallest_subarray_covering_set_attempt_one (paragraph : List [str ],
28
+ keywords : Set [str ]) -> Subarray :
29
+ subarr = collections .deque ([])
30
+ current_kwords = collections .Counter ()
31
+ left , right = 0 , len (paragraph )- 1
32
+ for i , word in enumerate (paragraph ):
33
+ if word in keywords :
34
+ current_kwords [word ] += 1
35
+ subarr .append (i )
36
+ while subarr and current_kwords [paragraph [subarr [0 ]]] > 1 :
37
+ current_kwords [paragraph [subarr [0 ]]] -= 1
38
+ subarr .popleft ()
39
+ if len (current_kwords ) == len (keywords ) and ((subarr [- 1 ] - subarr [0 ]) <= (right - left )):
40
+ left , right = subarr [0 ], subarr [- 1 ]
41
+ return Subarray (left , right )
42
+
11
43
12
44
def find_smallest_subarray_covering_set (paragraph : List [str ],
13
45
keywords : Set [str ]) -> Subarray :
14
- # TODO - you fill in here.
15
- return Subarray (0 , 0 )
46
+ counts = collections .Counter ()
47
+ best = Subarray (0 , len (paragraph )- 1 )
48
+ left = 0
49
+ for right , word in enumerate (paragraph ):
50
+ if word not in keywords :
51
+ continue
52
+ counts [word ] += 1
53
+
54
+ while left < len (paragraph ) and not (counts [paragraph [left ]] == 1 ):
55
+ if paragraph [left ] in counts :
56
+ counts [paragraph [left ]] -= 1
57
+ left += 1
58
+
59
+ if len (counts ) == len (keywords ) and ((right - left ) <= (best .end - best .start )):
60
+ best = Subarray (left , right )
61
+ return best
16
62
17
63
18
64
@enable_executor_hook
@@ -37,6 +83,19 @@ def find_smallest_subarray_covering_set_wrapper(executor, paragraph, keywords):
37
83
38
84
39
85
if __name__ == '__main__' :
86
+ """
87
+ cases = [
88
+ (["a", "b", "c", "b", "a", "d", "c", "a", "e", "a", "a", "b", "e"], set(["b", "c", "e"]), Subarray(6, 11)),
89
+ (["a", "b", "c", "e", "a"], set(["b", "c", "e"]), Subarray(1, 3)),
90
+ (["a", "b", "c", "e", "a", "e"], set(["b", "c", "e"]), Subarray(1, 3)),
91
+ (["b", "a", "b", "c", "e", "a", "e"], set(["b", "c", "e"]), Subarray(2, 4)),
92
+ (["b", "a", "c", "c", "c", "b", "c", "e", "a", "e"], set(["b", "c", "e"]), Subarray(5, 7))
93
+
94
+ ]
95
+ for paragraph, keywords, expected in cases:
96
+ actual = find_smallest_subarray_covering_set(paragraph, keywords)
97
+ assert expected == actual, f"\n paragraph: {paragraph}\n keywords: {keywords}\n {expected} != {actual}"
98
+ """
40
99
exit (
41
100
generic_test .generic_test_main (
42
101
'smallest_subarray_covering_set.py' ,
0 commit comments