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: Leetcode/Median_of_Two_Sorted_Arrays.cpp
+19-6
Original file line number
Diff line number
Diff line change
@@ -6,13 +6,27 @@
6
6
This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2)
7
7
8
8
Now, lets optimise it.
9
-
So, the sorted form of the given array is [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. Now suppose, on partitioning the above merged-sorted array in the mid-point, we get 5 elements on left and 5 elements on the right.
10
-
Now, we can get 5 elements by selecting {4 from left, 1 from right}, {3 from left, 2 from right}, {2 from left, 3 from right} and {1 from left, 4 from right}.
11
-
Lets analyse case-wise:
12
-
case 1: 4 from left, 1 from right
13
-
9
+
So, the sorted form of the given array is arr = [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out.
10
+
If we observe the sorted array carefully, then we notice that the 2 middle elements are arr[4] = 4 and arr[5] = 6, => arr[4] <= arr[5].
11
+
12
+
Thought process:
13
+
Now, since the arrays are sorted, so the binary searh may be able to solve the problem.
14
+
Observation 1: If we partition the sorted array arr into 2 halves, then for sure we know that there would be 5 elements on left half and 5 elements on right half.
15
+
Now, we can select 5 elements for right half from nums1 and nums2 combinedly and similarly the rest of the elements for the left half.
16
+
Example:
17
+
1. left => [1, 3, 4, 7, 2], right => [10, 12, 3, 6, 15]
18
+
2. left => [1, 3, 4, 2, 3], right => [7, 10, 12, 6, 15]
19
+
3. left => [1, 3, 2, 3, 6], right => [4, 7, 10, 12, 15]
20
+
21
+
Observation 2: All the elements on left half is lesser than all the elements on the right half.
22
+
Now, according to the observation, I have to check that all the elements in the left <= all the elements in the right. This can be done by just comparing the maximum of left half <= minimum of right half.
23
+
24
+
Hence, the problem boils down to a searching problem; but how to identify the binary search approach??
25
+
Suppose, we partition the element as example 1, then the max of left[] = 7 and min of right[] = 3, but according to the 2nd observation, it is not valid. So, in order to have a correct max in left, I need to reduce its value and consequestly, the min of right[] should be increased. That means, I have to move leftwards in nums1 to have a correct max value in left half.
0 commit comments