Skip to content

Commit 3e7dd5d

Browse files
feat(smallest-common-num): add smallest common num challenge)
1 parent 89ba06c commit 3e7dd5d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Problem: Find smallest common number in list of sorted arrays.
3+
e.g. array1: [1, 3, 5, 10, 20] array2: [2, 4, 5, 10, 20] array3: [2, 4, 10, 20]
4+
common elements = > 10 & 20 result = > 10
5+
Constraints:
6+
* Any number of arrays
7+
* Each array could be of any size
8+
* [execution time limit] 4 seconds(js)
9+
10+
10
11+
10
12+
10
13+
"""
14+
15+
16+
def smallest_common_num(arrays):
17+
idxs = [0] * len(arrays)
18+
19+
largest_num = float('-inf')
20+
largest_arrays_idxs = set()
21+
22+
while len(largest_arrays_idxs) != len(arrays):
23+
for idx, array in enumerate(arrays):
24+
if idxs[idx] >= len(array):
25+
return None
26+
27+
if array[idxs[idx]] > largest_num:
28+
largest_num = array[idxs[idx]]
29+
largest_arrays_idxs = {idx}
30+
elif array[idxs[idx]] == largest_num:
31+
largest_arrays_idxs.add(idx)
32+
33+
for idx in range(len(idxs)):
34+
if idx not in largest_arrays_idxs:
35+
idxs[idx] += 1
36+
37+
return largest_num
38+
39+
40+
print(smallest_common_num([[1, 3, 5, 10, 20],
41+
[1, 2, 4, 5, 10, 20],
42+
[2, 4, 10, 20]]))

0 commit comments

Comments
 (0)