forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-common-subsequence-between-sorted-arrays.py
More file actions
38 lines (33 loc) · 1.1 KB
/
longest-common-subsequence-between-sorted-arrays.py
File metadata and controls
38 lines (33 loc) · 1.1 KB
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
# Time: O(m * n)
# Space: O(l), l is min(len(arr) for arr in arrays)
class Solution(object):
def longestCommomSubsequence(self, arrays):
"""
:type arrays: List[List[int]]
:rtype: List[int]
"""
result = min(arrays, key=lambda x: len(x))
for arr in arrays:
new_result = []
i, j = 0, 0
while i != len(result) and j != len(arr):
if result[i] < arr[j]:
i += 1
elif result[i] > arr[j]:
j += 1
else:
new_result.append(result[i])
i += 1
j += 1
result = new_result
return result
# Time: O(m * n)
# Space: O(k), k is min(m * n, max(x for arr in arrays for x in arr))
import collections
class Solution2(object):
def longestCommomSubsequence(self, arrays):
"""
:type arrays: List[List[int]]
:rtype: List[int]
"""
return [num for num, cnt in collections.Counter(x for arr in arrays for x in arr).iteritems() if cnt == len(arrays)]