Median of Two Sorted Arrays - Solution & Explanation
Problem Statement
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] <= 106
Approach Overview
Problem 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.
Approach 1: Binary Search on Smaller Array
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.
Complexity
Time complexity: O(log(min(m,n))). Space complexity: O(1).
Approach 2: Merge and Find Median
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.
Complexity
Time complexity: O(m + n). Space complexity: O(m + n).
Approach 3: Divide and Conquer
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:
- If
i geq m, it means that the interval[i, m)of arraynums1is empty, so directly returnnums2[j + k - 1]; - If
j geq n, it means that the interval[j, n)of arraynums2is empty, so directly returnnums1[i + k - 1]; - If
k = 1, it means to find the first number, so just return the minimum ofnums1[i]andnums2[j]; - Otherwise, we find the
\left\lfloor\frac{k}{2}\right\rfloor-th number in the two arrays, denoted asxandy. (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 ofxandy:- If
x leq y, it means that the\left\lfloor\frac{k}{2}\right\rfloor-th number of arraynums1cannot be thek-th smallest number, so we can exclude the interval[i, i + \left\lfloor\frac{k}{2}\right\rfloor)of arraynums1, and recursively callf(i + \left\lfloor\frac{k}{2}\right\rfloor, j, k - \left\lfloor\frac{k}{2}\right\rfloor). - If
x > y, it means that the\left\lfloor\frac{k}{2}\right\rfloor-th number of arraynums2cannot be thek-th smallest number, so we can exclude the interval[j, j + \left\lfloor\frac{k}{2}\right\rfloor)of arraynums2, and recursively callf(i, j + \left\lfloor\frac{k}{2}\right\rfloor, k - \left\lfloor\frac{k}{2}\right\rfloor).
- If
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.
Code
Python
Java
C++
Go
TypeScript
JavaScript
C#
PHP
Nim
C
Complexity Comparison
| 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 | — |
Detailed Complexity Analysis
| 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 |
Video Solution
Median of Two Sorted Arrays - Binary Search - Leetcode 4 • NeetCode • 724,399 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Median of Two Sorted Arrays easy or hard?
Median of Two Sorted Arrays Python/Java solution
What is the best approach for Median of Two Sorted Arrays?
Is Median of Two Sorted Arrays asked at Google/Amazon/Meta?
What data structure is used in Median of Two Sorted Arrays?
What is the time complexity of Median of Two Sorted Arrays?
How to solve Median of Two Sorted Arrays in O(log(min(m,n)))?
Ready to solve this problem?
Practice Median of Two Sorted Arrays with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor