-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathp17_18.py
53 lines (39 loc) · 1.35 KB
/
p17_18.py
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
from typing import List
from collections import defaultdict
# Method: Two pointer, keep track of elements
# Time: O(l)
# Space: O(s)
def longest_superseq(longer: List[int], shorter: List[int]) -> List[int]:
short_set = set(shorter)
count_now = defaultdict(int)
start = 0
number_uniq = 0
min_seq_now = float("inf")
min_seq_indexes = (-1, -1)
for i in range(len(longer)):
x = longer[i]
if x in short_set:
if count_now[x] == 0:
number_uniq += 1
count_now[x] += 1
while number_uniq == len(shorter) and start < i:
current_subseq_len = i - start + 1
if current_subseq_len < min_seq_now:
min_seq_now = current_subseq_len
min_seq_indexes = (start, i)
if longer[start] in short_set:
count_now[longer[start]] -= 1
if count_now[longer[start]] == 0:
number_uniq -= 1
start += 1
return list(min_seq_indexes)
if __name__ == "__main__":
exs = [
([1, 5, 9], [7, 5, 9, 0, 2, 1, 3, 5, 7, 9, 1, 1, 5, 8, 8, 9, 7]),
([1, 2, 3], [1, 1, 2, 2, 2, 3, 3, 9, 9, 2, 1, 1, 3]),
]
for shorter, longer in exs:
print(
f"Between {longest_superseq(longer,shorter)}, "
f"you will find {shorter} in {longer}"
)