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)).
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == mnums2.length == n0 <= m <= 10000 <= n <= 10001 <= m + n <= 2000-106 <= nums1[i], nums2[i] <= 106Problem Overview: You are given two sorted arrays of sizes m and n. The goal is to compute the median of the combined sorted sequence without explicitly building the full merged array.
Approach 1: Merge and Find Median (O(m + n) time, O(1) or O(m+n) space)
This approach simulates the merge step from merge sort. Use two pointers to iterate through both arrays in sorted order until you reach the middle element of the combined length. If the total length is odd, the median is the middle value. If it is even, the median is the average of the two middle values. The idea is simple and reliable because both arrays are already sorted, but the algorithm still scans up to m + n elements.
This solution is useful when constraints are small or when you want a quick implementation during practice. It relies on sequential iteration over arrays and does not use advanced optimization.
Approach 2: Binary Search on Smaller Array (O(log(min(m,n))) time, O(1) space)
The optimal solution treats the problem as a partitioning task. Instead of merging arrays, perform binary search on the smaller array to find a partition such that the left halves of both arrays contain exactly half of the total elements. The key condition: the maximum element on the left side must be less than or equal to the minimum element on the right side.
During each step, choose a partition index in the smaller array and compute the corresponding partition in the second array. Check boundary values around the partitions. If the ordering condition fails, move the binary search window left or right. Once the correct partition is found, compute the median using the boundary elements.
This technique uses properties of sorted arrays and reduces the search space logarithmically. It combines ideas from arrays, binary search, and divide and conquer to achieve optimal performance.
Recommended for interviews: Interviewers typically expect the binary search partition solution with O(log(min(m,n))) time complexity. The merge approach demonstrates baseline understanding, but the partition method shows strong algorithmic reasoning and comfort with binary search edge cases.
This approach leverages binary search to reduce the problem to a smaller size, achieving the desired O(log(m + n)) complexity. The strategy involves performing binary search on the smaller array to find the perfect partition point.
In this C solution, we first ensure that we perform the binary search on the smaller of the two arrays to maintain efficiency. We set bounds for `i` and adjust those bounds based on comparisons calculated at each step. The correct partitioning of elements between the two arrays determines the median.
Time complexity: O(log(min(m,n))). Space complexity: O(1).
This approach focuses on merging the two sorted arrays as naturally done in merge sort, and then finding the median directly from the merged result. Though this solution has a higher time complexity, it's easier to implement and understand.
The C implementation uses an auxiliary array to merge the two sorted arrays into one. After merging, we calculate the median of the merged array based on its even or odd length. Memory allocation and deallocation are crucial to manage space efficiently.
Time complexity: O(m + n). Space complexity: O(m + n).
The problem requires the time complexity of the algorithm to be O(log (m + n)), so we cannot directly traverse the two arrays, but need to use the binary search method.
If m + n is odd, then the median is the \left\lfloor\frac{m + n + 1}{2}\right\rfloor-th number; if m + n is even, then the median is the average of the \left\lfloor\frac{m + n + 1}{2}\right\rfloor-th and the \left\lfloor\frac{m + n + 2}{2}\right\rfloor-th numbers. In fact, we can unify it as the average of the \left\lfloor\frac{m + n + 1}{2}\right\rfloor-th and the \left\lfloor\frac{m + n + 2}{2}\right\rfloor-th numbers.
Therefore, we can design a function f(i, j, k), which represents the k-th smallest number in the interval [i, m) of array nums1 and the interval [j, n) of array nums2. The median is the average of f(0, 0, \left\lfloor\frac{m + n + 1}{2}\right\rfloor) and f(0, 0, \left\lfloor\frac{m + n + 2}{2}\right\rfloor).
The implementation idea of the function f(i, j, k) is as follows:
i geq m, it means that the interval [i, m) of array nums1 is empty, so directly return nums2[j + k - 1];j geq n, it means that the interval [j, n) of array nums2 is empty, so directly return nums1[i + k - 1];k = 1, it means to find the first number, so just return the minimum of nums1[i] and nums2[j];\left\lfloor\frac{k}{2}\right\rfloor-th number in the two arrays, denoted as x and y. (Note, if a certain array does not have the \left\lfloor\frac{k}{2}\right\rfloor-th number, then we regard the \left\lfloor\frac{k}{2}\right\rfloor-th number as +infty.) Compare the size of x and y:x leq y, it means that the \left\lfloor\frac{k}{2}\right\rfloor-th number of array nums1 cannot be the k-th smallest number, so we can exclude the interval [i, i + \left\lfloor\frac{k}{2}\right\rfloor) of array nums1, and recursively call f(i + \left\lfloor\frac{k}{2}\right\rfloor, j, k - \left\lfloor\frac{k}{2}\right\rfloor).x > y, it means that the \left\lfloor\frac{k}{2}\right\rfloor-th number of array nums2 cannot be the k-th smallest number, so we can exclude the interval [j, j + \left\lfloor\frac{k}{2}\right\rfloor) of array nums2, and recursively call f(i, j + \left\lfloor\frac{k}{2}\right\rfloor, k - \left\lfloor\frac{k}{2}\right\rfloor).The time complexity is O(log(m + n)), and the space complexity is O(log(m + n)). Here, m and n are the lengths of arrays nums1 and nums2 respectively.
Python
Java
C++
Go
TypeScript
JavaScript
C#
PHP
Nim
C
| Approach | Complexity |
|---|---|
| Binary Search on Smaller Array | Time complexity: O(log(min(m,n))). Space complexity: O(1). |
| Merge and Find Median | Time complexity: O(m + n). Space complexity: O(m + n). |
| Divide and Conquer | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Merge and Find Median | O(m + n) | O(1) or O(m+n) | Simple implementation when constraints are small or during initial problem understanding |
| Binary Search on Smaller Array | O(log(min(m,n))) | O(1) | Best choice for large inputs and expected solution in technical interviews |
Median of Two Sorted Arrays - Binary Search - Leetcode 4 • NeetCode • 690,245 views views
Watch 9 more video solutions →Practice Median of Two Sorted Arrays with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor