You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+71
Original file line number
Diff line number
Diff line change
@@ -531,3 +531,74 @@ The time complexity for this algorithm is $O(n)$, as we only iterate once with t
531
531
Well done, we can't really do anything better here.
532
532
533
533
#### 4. To Be Continued
534
+
535
+
Ok, median — the middle value of an array, or an average of the two middle values if the array is even. We are going to start really naively.
536
+
537
+
First idea (working) that comes to my mind is to merge the arrays, preserving the order, and return middle. That's not the greatest, as: 1. I'm not doing it in-place, 2. I'm merging naively.
538
+
539
+
```python
540
+
deffindMedianSortedArrays(self, nums1, nums2):
541
+
arr = []
542
+
j =0
543
+
544
+
for i inrange(len(nums1)):
545
+
while j <len(nums2) and nums2[j] < nums1[i]:
546
+
arr.append(nums2[j])
547
+
j +=1
548
+
arr.append(nums1[i])
549
+
while j <len(nums2):
550
+
arr.append(nums2[j])
551
+
j +=1
552
+
553
+
n =len(arr)
554
+
if n %2==0:
555
+
return (arr[n//2-1] + arr[n//2]) /2.0
556
+
else:
557
+
return arr[n//2]
558
+
```
559
+
560
+
Time complexity for this is $O(m + n)$ (linear analog to a single input functions), so could be worse, but descriptions suggests that we should be doing that in $O(\log(m+n))$. Space complexity is also $O(m+n)$, as the array we build holds as many elements, as the two inputs combined. Not sure if we can make it better yet.
561
+
562
+
##### More optimal, two-pointer with no array
563
+
564
+
Ok, I kind of cheated this one. It's basically the same idea as above, but we are not holding the big ass new array. This way we bring the space complexity $O(n+m) \rightarrow O(1)$. I couldn't quite figure out the termination conditions for an implementation that's not using temporary values `v1` and `v2`.
565
+
566
+
```python
567
+
deffindMedianSortedArrays(self, nums1, nums2):
568
+
n =len(nums1)
569
+
m =len(nums2)
570
+
nm = n + m
571
+
middle = nm %2!=0
572
+
target = nm //2
573
+
i =0
574
+
j =0
575
+
v1 =0
576
+
v2 =0
577
+
578
+
for _ inrange(0, target+1):
579
+
v2 = v1
580
+
if i < n and j < m:
581
+
if nums1[i] < nums2[j]:
582
+
v1 = nums1[i]
583
+
i +=1
584
+
else:
585
+
v1 = nums2[j]
586
+
j +=1
587
+
elif i < n:
588
+
v1 = nums1[i]
589
+
i +=1
590
+
else:
591
+
v1 = nums2[j]
592
+
j +=1
593
+
594
+
if middle:
595
+
return v1
596
+
else:
597
+
return (v1+v2) /2.0
598
+
```
599
+
600
+
The time complexity is again $O(n+m)$, as we may have to iterate over both arrays.
0 commit comments