Skip to content

Commit 3a0d674

Browse files
committed
4: almost completed, missing optimal, and binary search .py
1 parent 30ab10d commit 3a0d674

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

README.md

+71
Original file line numberDiff line numberDiff line change
@@ -531,3 +531,74 @@ The time complexity for this algorithm is $O(n)$, as we only iterate once with t
531531
Well done, we can't really do anything better here.
532532

533533
#### 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+
def findMedianSortedArrays(self, nums1, nums2):
541+
arr = []
542+
j = 0
543+
544+
for i in range(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+
def findMedianSortedArrays(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 _ in range(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.
601+
602+
##### Optimal, Binary search
603+
604+

binarysearch.py

Whitespace-only changes.

0 commit comments

Comments
 (0)