Skip to content

Commit d4369a7

Browse files
authored
Merge pull request #406 from KC10201/main
4-Median-Of-Two-Sorted-Arrays: Add Logarithmic Solution
2 parents caa31af + 14e1eee commit d4369a7

File tree

2 files changed

+62
-4
lines changed

2 files changed

+62
-4
lines changed

cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/*
22
Given root of binary tree, determine if it's valid (left all < curr, right all > curr)
3-
3+
44
Inorder traversal & check if prev >= curr, recursive/iterative solutions
5-
5+
66
Time: O(n)
77
Space: O(n)
88
*/

java/4-Median-of-Two-Sorted-Arrays.java

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
/*Brute-force solution (Linear time)*/
2-
1+
/*Brute-force solution (Linear)*/
2+
/*
3+
// Runtime: O(m+n)
4+
// Extra Space: O(m+n)
5+
//
36
class Solution {
47
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
58
int m = nums1.length;
@@ -18,3 +21,58 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2) {
1821
} else return (float)nums[(m+n-1)/2];
1922
}
2023
}
24+
*/
25+
/* Optimized solution (Logarithmic) */
26+
27+
// Runtime: O(log(min(m,n)))
28+
// Extra Space: O(1)
29+
30+
class Solution {
31+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
32+
int m = nums1.length;
33+
int n = nums2.length;
34+
35+
if(m > n){
36+
return findMedianSortedArrays(nums2, nums1);
37+
}
38+
39+
int total = m + n;
40+
int half = (total + 1) / 2;
41+
42+
int left = 0;
43+
int right = m;
44+
45+
var result = 0.0;
46+
47+
while(left <= right){
48+
int i = left + (right - left) / 2;
49+
int j = half - i;
50+
51+
// get the four points around possible median
52+
int left1 = (i > 0) ? nums1[i - 1] : Integer.MIN_VALUE;
53+
int right1 = (i < m) ? nums1[i] : Integer.MAX_VALUE;
54+
int left2 = (j > 0) ? nums2[j - 1] : Integer.MIN_VALUE;
55+
int right2 = (j < n) ? nums2[j] : Integer.MAX_VALUE;
56+
57+
// partition is correct
58+
if (left1 <= right2 && left2 <= right1) {
59+
// even
60+
if (total % 2 == 0) {
61+
result = (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0;
62+
// odd
63+
} else {
64+
result = Math.max(left1, left2);
65+
}
66+
break;
67+
}
68+
// partition is wrong (update left/right pointers)
69+
else if (left1 > right2) {
70+
right = i - 1;
71+
} else {
72+
left = i + 1;
73+
}
74+
}
75+
76+
return result;
77+
}
78+
}

0 commit comments

Comments
 (0)