Skip to content

Commit f2049b6

Browse files
committed
Added question 4.
1 parent dc7ab0f commit f2049b6

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#4. Median of Two Sorted Arrays
2+
3+
## Linear Solution
4+
- Run-time: O(N)
5+
- Space: O(1)
6+
- N = Number of elements in both lists
7+
8+
For the first solution, lets dissect what it means to find a median in two sorted lists.
9+
10+
Some properties we know are:
11+
- Total length of both lists.
12+
- Both lists are sorted.
13+
14+
If you had one list, it would be as easy as index = total length // 2 and list[index] as the median if even, else list[index+1] if odd.
15+
Since we know the total length, we can still find how many times we need to traverse until we hit a median.
16+
With one list, we can treat the list as having a left array and a right array.
17+
Knowing how big the left array would be as one list and the fact that both lists are sorted, we can traverse the left side of both lists until we have traversed enough indexes.
18+
When the left most index of both lists are found, the left index + 1 of both lists would be part of the right array.
19+
20+
```
21+
class Solution:
22+
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
23+
24+
def get_right_most_indexes_of_array1():
25+
n_moves_to_med = (len(nums1) + len(nums2)) // 2
26+
left1_idx = left2_idx = -1
27+
while n_moves_to_med and left1_idx+1 < len(nums1) and left2_idx+1 < len(nums2):
28+
n_moves_to_med -= 1
29+
if nums1[left1_idx+1] < nums2[left2_idx+1]:
30+
left1_idx += 1
31+
else:
32+
left2_idx += 1
33+
while n_moves_to_med and left1_idx+1 < len(nums1):
34+
n_moves_to_med -= 1
35+
left1_idx += 1
36+
while n_moves_to_med and left2_idx+1 < len(nums2):
37+
n_moves_to_med -= 1
38+
left2_idx += 1
39+
return (left1_idx, left2_idx)
40+
41+
left1_idx, left2_idx = get_right_most_indexes_of_array1()
42+
# left most number of array2
43+
n2 = min(nums1[left1_idx+1] if 0 <= left1_idx+1 < len(nums1) else float('inf'),
44+
nums2[left2_idx+1] if 0 <= left2_idx+1 < len(nums2) else float('inf'))
45+
if (len(nums1) + len(nums2)) % 2 == 0: # is even?
46+
# right most number of array1
47+
n1 = max(nums1[left1_idx] if 0 <= left1_idx < len(nums1) else float('-inf'),
48+
nums2[left2_idx] if 0 <= left2_idx < len(nums2) else float('-inf'))
49+
return (n1 + n2) / 2
50+
return n2 # is odd
51+
```

0 commit comments

Comments
 (0)