Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
nums1.length == mnums2.length == n0 <= m <= 10000 <= n <= 10001 <= m + n <= 2000-10⁶ <= nums1[i], nums2[i] <= 10⁶The simplest way to find the requested median is to directly merge these two already sorted arrays together using Two Pointers into a massive array. Then, locate the exact middle coordinate of this new structure.
merged_array.nums1 or nums2, picking the smallest of the two pointers and appending it.merged_array is fully populated, find the median by taking merged[(len)/2].Thoughts: While this solution conceptually makes sense, it strictly operates at an $O(m + n)$ runtime limit, which doesn't fulfill the $O(log(m+n))$ constraint! We must not physically merge the arrays.
By definition, a median splits an entire dataset exactly into two halves: a Left Half (all smaller values) and a Right Half (all greater values). Since our arrays are already strictly sorted, if we can dynamically partition both arrays into left and right chunks such that the combined Left is exactly half the total size and all left values are <= all right values, we've found the mathematical median without assembling the array.
We binary search over the strictly smaller array (let's call it A) to find a partition. Using this, we immediately know where the partition in B must be to maintain the "exactly half the elements on the left side" rule: j = total_half - i - 2.
A is the smaller array to improve speed and prevent out-of-bounds indexing in B. Set half = (len(A) + len(B)) // 2.i on A from 0 to len(A)-1.j in B via j = half - i - 2.Aleft, Aright, Bleft, Bright, substituting $\pm\infty$ for out-of-bounds values.Aleft <= Bright AND Bleft <= Aright), the partition is valid! Return the median formula based on total parity.Aleft > Bright, the partition line in A is physically placed too far right. We must shrink right bound: r = i - 1.Bleft > Aright, the partition line is too far left. Go right: l = i + 1.
Discussion
…