Algorithm Day69 - Median of Two Sorted Arrays
🧩 Problem Description
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall runtime complexity should be O(log (m+n)).
💬 Examples
Example 1
1 | Input: nums1 = [1,3], nums2 = [2] |
Example 2
1 | Input: nums1 = [1,2], nums2 = [3,4] |
Example 3
1 | Input: nums1 = [0,0], nums2 = [0,0] |
💡 Intuition
We need to find the k-th smallest element in two sorted arrays efficiently.
- Partition both arrays so that the left half and right half are balanced.
- Ensure all elements in the left half are ≤ all elements in the right half.
- Depending on the total length being odd/even, return middle or average of two middle values.
This can be solved with binary search on the partition.
🔢 Java Code (Binary Search Partition)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(log(min(m, n))) — binary search only on smaller array.
- Space: O(1).
✍️ Summary
- Partition both arrays using binary search.
- Compare partition edges to decide where to move.
- Handle odd/even total length cases.
Related problems
lc-33— Search in Rotated Sorted Arraylc-153— Find Minimum in Rotated Sorted Array