Median of Two Sorted Arrays
Problem Statement
You are given two sorted arrays, nums1 (size m) and nums2 (size n). Imagine putting all m + n numbers together in sorted order. Return the median of that combined list:
- If the total count is odd, the median is the single middle number.
- If it is even, the median is the average of the two middle numbers (this can be a
.5value).
The expected time is O(log(m + n)). One of the arrays may be empty.
Two integer arrays nums1 and nums2, each sorted in non-decreasing order.
A double: the median of all the numbers from both arrays.
All numbers together: [1, 2, 3]. Three numbers, so the middle one, 2, is the median.
All numbers together: [1, 2, 3, 4]. Four numbers, so the median is (2 + 3) / 2 = 2.5.
- β’ 0 β€ m, n β€ 1000
- β’ 1 β€ m + n β€ 2000
- β’ β10^6 β€ nums1[i], nums2[i] β€ 10^6
- β’ Both arrays are sorted in non-decreasing order (duplicates allowed).
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Merge both arrays into a new sorted array and read the middle
Same two-pointer merge, but stop at the middle and keep only the last two values
Binary search how many values the left half takes from the smaller array; check the 4 border values
Merge the two sorted arrays like in merge sort (two pointers, always take the smaller front value). Then the median is all[total / 2] when total is odd, or the average of all[total/2 β 1] and all[total/2] when it is even.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Binary Search translate into production architectures and low-level memory mechanics.