Logarithmic Median of Two Sorted Arrays
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given two integer sequences nums1 (of length m) and nums2 (of length n), each already arranged in ascending (non-decreasing) order, implement find_median_sorted_arrays(nums1, nums2) to return the median of all m + n numbers as a float.
One of the two sequences may be empty, provided that m + n >= 1. Suppose combined denotes all m + n elements placed in non-decreasing order (0-indexed):
- When
m + nis odd, the median is the single central valuefloat(combined[(m + n) // 2]). - When
m + nis even, the median is the arithmetic mean of the two central values:(combined[(m + n) // 2 - 1] + combined[(m + n) // 2]) / 2.0.
Your algorithm must run in O(log(m + n)) time and use O(1) auxiliary memory—you may not materialize a combined list or walk linearly across the inputs.
Examples
Example 1
- Input:
nums1 = [2, 8],nums2 = [4, 6, 10] - Output:
6.0 - Explanation: The combined sorted order is
[2, 4, 6, 8, 10](5values total), whose middle entry at index2is6.0.
Example 2
- Input:
nums1 = [-4, 3],nums2 = [6, 11] - Output:
4.5 - Explanation: Across the
4sorted elements[-4, 3, 6, 11], the two inner values are3and6, averaging to(3 + 6) / 2.0 = 4.5.
Example 3
- Input:
nums1 = [],nums2 = [9] - Output:
9.0 - Explanation:
nums1contributes zero elements, leaving[9]with median9.0.
Example 4
- Input:
nums1 = [-2, 4],nums2 = [4, 4] - Output:
4.0 - Explanation: Repeated numbers are preserved (
[-2, 4, 4, 4]); the two middle entries are both4, yielding4.0.
Constraints
0 <= len(nums1), len(nums2) <= 10^5len(nums1) + len(nums2) >= 1-2^31 <= nums1[i], nums2[j] <= 2^31 - 1nums1andnums2are each sorted in non-decreasing order.- Time complexity must be
O(log(m + n))and auxiliary space complexity must beO(1).
Step-by-step walkthrough
Understand the goal: find the middle without merging
We are given two sorted integer arrays
nums1(lengthm) andnums2(lengthn), wherem + n >= 1. Imagine merging them into one sorted array of lengthtotal_len = m + n:Odd total (m + n = 5): [ 2, 4, | 6 |, 8, 10 ] -> middle index 2 -> median = 6.0 Even total (m + n = 4): [-4, | 3, 6 |, 11 ] -> average of indices 1 & 2 -> (3 + 6) / 2 = 4.5Merging the two arrays with two pointers takes
O(m + n)time (up to200,000steps). Our target isO(log(m + n))time andO(1)extra space, which rules out building a merged array or even walking linearly to the middle. Instead, we need a way to jump straight to the median boundary using binary search.Reframe "median" as a balanced cut across both arrays
Think about what the median actually separates: it splits all
total_lennumbers into a left half containing the smallest numbers and a right half containing the largest numbers.Let's set the exact size of the left half to:
left_half_size = (total_len + 1) // 2Why add
+ 1before integer division// 2? Check both cases:- When
total_len = 5(odd):left_half_size = (5 + 1) // 2 = 3. The left half holds 3 elements and the right half holds 2, so the single middle element sits at the very top of the left half (max(left_half)). - When
total_len = 4(even):left_half_size = (4 + 1) // 2 = 2. Both halves hold 2 elements, so the median is the average ofmax(left_half)andmin(right_half).
So if we can figure out which elements belong in the left half such that every number on the left is
<=every number on the right, we immediately know the median!- When
Link the two cuts and check only four border numbers
Because both
nums1andnums2are already sorted, the smallest elements contributed bynums1must be a prefixnums1[0 : cut1]of lengthcut1, and the smallest elements contributed bynums2must be a prefixnums2[0 : cut2]of lengthcut2.Crucially,
cut1andcut2are locked together because the total number of elements on the left must equalleft_half_size:cut2 = left_half_size - cut1Picking
cut1automatically determinescut2! Look at the four border elements sitting right next to the two cuts:nums1: [ ... left1 | right1 ... ] left1 = nums1[cut1 - 1], right1 = nums1[cut1] nums2: [ ... left2 | right2 ... ] left2 = nums2[cut2 - 1], right2 = nums2[cut2] <-- left --> | <-- right -->When is every left element
<=every right element? -left1 <= right1is already guaranteed becausenums1is sorted. -left2 <= right2is already guaranteed becausenums2is sorted. - So we only need to check the two cross-array pairs: 1.left1 <= right22.left2 <= right1What if a cut sits at the very beginning (
cut1 == 0, meaning we took zero elements fromnums1) or the very end (cut1 == m, meaning we took all ofnums1)? Then there is no element on that side of the cut, so we usefloat("-inf")for a missing left neighbor andfloat("inf")for a missing right neighbor. Minus infinity is always<=everything on the right, and plus infinity is always>=everything on the left!Why binary search works — and why we search the shorter array
Suppose our trial
cut1fails one of the two cross-checks. Which way shouldcut1move?- Case 1 (
left1 > right2): The last element we took fromnums1(left1) is too big — it belongs in the right half! We took too many elements fromnums1, so we must movecut1left:hi = cut1 - 1. - Case 2 (
left2 > right1): The last element we took fromnums2(left2) is bigger thanright1! Taking more elements fromnums1pushescut1right and simultaneously pullscut2 = left_half_size - cut1left, shrinkingleft2. So we movecut1right:lo = cut1 + 1.
Notice why we swap first so
nums1is the shorter array (m <= n): we binary-searchcut1across[0, m], and we needcut2 = left_half_size - cut1to always stay inside[0, n]. Let's verify both extremes whenm <= n:- Smallest
cut2(atcut1 = m):(m + n + 1) // 2 - m = (n - m + 1) // 2 >= 0becausen >= m. - Largest
cut2(atcut1 = 0):(m + n + 1) // 2 <= (n + n + 1) // 2 = nbecausem <= n.
So
cut2can never go negative or exceedn! Even better, binary-searching the shorter array takesO(log(min(m, n)))steps, which is always withinO(log(m + n)).- Case 1 (
Write the binary search loop
Putting those pieces together gives a short, clean
while lo <= hi:loop:if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1 m = len(nums1) n = len(nums2) total_len = m + n left_half_size = (total_len + 1) // 2 lo = 0 hi = m while lo <= hi: cut1 = (lo + hi) // 2 cut2 = left_half_size - cut1 left1 = nums1[cut1 - 1] if cut1 > 0 else float("-inf") right1 = nums1[cut1] if cut1 < m else float("inf") left2 = nums2[cut2 - 1] if cut2 > 0 else float("-inf") right2 = nums2[cut2] if cut2 < n else float("inf") if left1 > right2: hi = cut1 - 1 elif left2 > right1: lo = cut1 + 1 else: left_max = max(left1, left2) if total_len % 2 == 1: return float(left_max) right_min = min(right1, right2) return (left_max + right_min) / 2.0Trace Examples 1, 2, and 3
Example 1: nums1 = [2, 8] (m=2), nums2 = [4, 6, 10] (n=3) m <= n already holds; total_len = 5 (odd), left_half_size = (5 + 1) // 2 = 3 - Round 1: lo=0, hi=2 -> cut1=1, cut2=2 nums1: [ 2 | 8 ] -> left1 = 2, right1 = 8 nums2: [ 4, 6 | 10 ] -> left2 = 6, right2 = 10 Check: 2 <= 10 and 6 <= 8 -> VALID! Odd total -> float(max(2, 6)) = 6.0 Example 2: nums1 = [-4, 3] (m=2), nums2 = [6, 11] (n=2) total_len = 4 (even), left_half_size = (4 + 1) // 2 = 2 - Round 1: lo=0, hi=2 -> cut1=1, cut2=1 left1=-4, right1=3, left2=6, right2=11 -> left2 (6) > right1 (3) -> lo = 2 - Round 2: lo=2, hi=2 -> cut1=2, cut2=0 left1=3, right1=+inf, left2=-inf, right2=6 -> VALID! Even total -> (max(3, -inf) + min(+inf, 6)) / 2.0 = (3 + 6) / 2.0 = 4.5 Example 3: nums1 = [] (m=0), nums2 = [9] (n=1) total_len = 1 (odd), left_half_size = 1 - Round 1: lo=0, hi=0 -> cut1=0, cut2=1 left1=-inf, right1=+inf, left2=9, right2=+inf -> VALID! -> 9.0Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float: # Always binary-search on the shorter array so cut2 = left_half_size - cut1 # is guaranteed to stay within [0, len(nums2)] without out-of-bounds indices. if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1 m = len(nums1) n = len(nums2) total_len = m + n # Size of the combined left partition; +1 puts the single middle element on the left when odd. left_half_size = (total_len + 1) // 2 # Search range [lo, hi] over cut1 = count of elements taken from nums1 (0 .. m inclusive). lo = 0 hi = m while lo <= hi: cut1 = (lo + hi) // 2 cut2 = left_half_size - cut1 # Border values immediately left and right of each cut. # Use -inf / +inf sentinels when a cut sits at index 0 or n/m so boundary checks stay valid. left1 = nums1[cut1 - 1] if cut1 > 0 else float("-inf") right1 = nums1[cut1] if cut1 < m else float("inf") left2 = nums2[cut2 - 1] if cut2 > 0 else float("-inf") right2 = nums2[cut2] if cut2 < n else float("inf") if left1 > right2: # Left partition took an element from nums1 larger than nums2's right side; move cut1 left. hi = cut1 - 1 elif left2 > right1: # Left partition took too few from nums1 (and too many from nums2); move cut1 right. lo = cut1 + 1 else: # Valid partition found: every element on the left is <= every element on the right. left_max = max(left1, left2) if total_len % 2 == 1: return float(left_max) right_min = min(right1, right2) return (left_max + right_min) / 2.0 raise ValueError("Input arrays must be sorted in non-decreasing order.")✅ Submit now — all tests should pass.
Intuition & how it works
Imagine two lines of students already sorted from shortest to tallest, and your job is to find the median height (the middle value when the total count is odd, or the average of the two middle values when even) without merging everyone into one giant line. Instead of moving students around, you just place one divider rope across Line 1 and a second divider rope across Line 2 so that the total number of students standing to the left of both ropes equals half the group ((m + n + 1) // 2). Once you pick where Rope 1 goes (cut1 students from nums1), Rope 2's spot (cut2 = left_half_size - cut1 students from nums2) is forced automatically! You only have to check whether the tallest student left of Rope 1 is <= the shortest student right of Rope 2, and vice versa — and because moving Rope 1 right makes its value grow while pushing Rope 2 left makes its value shrink, that monotonicity (values changing cleanly in one direction as the index increases) lets us find the exact rope position with binary search (repeatedly halving the range of candidate positions [lo, hi]).
Why does the obvious approach fall short? Concatenating and sorting takes O((m + n) log(m + n)) time and O(m + n) memory, and even a two-pointer walk up to the middle still reads (m + n) / 2 elements — up to 100,000 reads when m = n = 100,000. Binary-searching the partition (the pair of cuts splitting all elements into smaller and larger halves) on the shorter array finds the answer in at most ~17 loop iterations!
Let's trace Example 2 (nums1 = [-4, 3] and nums2 = [6, 11]), where total_len = 4 and left_half_size = (4 + 1) // 2 = 2, using sentinel values (-inf and +inf placeholder extremes used when a cut sits at the very start or end of an array):
1. lo = 0, hi = 2 -> try cut1 = 1, so cut2 = 2 - 1 = 1:
nums1: [ -4 | 3 ] -> left1 = -4, right1 = 3
nums2: [ 6 | 11 ] -> left2 = 6, right2 = 11
Cross-check: left2 (6) > right1 (3) -> took too few from nums1! Move lo = 2.
2. lo = 2, hi = 2 -> try cut1 = 2, so cut2 = 2 - 2 = 0:
nums1: [ -4, 3 | ] -> left1 = 3, right1 = +inf
nums2: [ | 6, 11 ] -> left2 = -inf, right2 = 6
Cross-check: 3 <= 6 and -inf <= +inf -> valid partition!
Even total -> (max(3, -inf) + min(+inf, 6)) / 2.0 = (3 + 6) / 2.0 = 4.5
Complexity
Let m and n be the lengths of nums1 and nums2.
- Time:
O(log(min(m, n))), which satisfies and improves upon theO(log(m + n))requirement. We swap references inO(1)sonums1has lengthmin(m, n), and the binary search starts withmin(m, n) + 1candidate cut positions (0throughmin(m, n)), cutting the search range in half on every iteration while doingO(1)index reads and comparisons per step. - Space:
O(1). Rebindingnums1, nums2 = nums2, nums1only swaps two local variable references without copying either array, and the loop maintains just a handful of integer indices and four border values.
Edge cases
- One array is empty (
[]and[9], or[]and[4, 7]): After swapping,m = 0, solo = hi = 0,cut1 = 0,cut2 = left_half_size,left1 = -inf,right1 = +inf, and the median is read directly fromnums2on the very first iteration. - Single total element (
[]and[9]):total_len = 1is odd,left_half_size = 1, and the odd branch returnsfloat(max(left1, left2))without touchingright_min(+inf). - Disjoint value ranges (
[-4, 3]and[6, 11]): The valid cut sits all the way atcut1 = morcut1 = 0; the-infand+infsentinels keep all comparisons well-defined without special-caseifbranches. - Repeated values across the cut (
[-2, 4]and[4, 4]): Multiplecut1positions can satisfyleft1 <= right2andleft2 <= right1, and every valid split yieldsleft_max = 4andright_min = 4, returning4.0. - Negative numbers and 32-bit integer extremes (
-2^31and2^31 - 1): Python integers have arbitrary precision, soleft_max + right_minnever overflows (in C++ or Java, cast tolongordoublebefore adding two2147483647values). - Wildly unbalanced sizes (
m = 1,n = 100,000): Swapping so we search the 1-element array finishes in at most 2 iterations (cut1 = 0orcut1 = 1).
Common mistakes
- Binary-searching the longer array without clamping bounds: If
len(nums1) > len(nums2), pickingcut1near0makescut2 = left_half_size - cut1 > len(nums2), and pickingcut1nearlen(nums1)makescut2 < 0(which silently indexes from the end ofnums2in Python!). Swapping solen(nums1) <= len(nums2)prevents both bugs completely. - Forgetting edge sentinels when
cut1 == 0orcut2 == 0: Evaluatingnums1[cut1 - 1]whencut1 == 0readsnums1[-1](the largest element ofnums1!) instead of-infin Python, causing baffling wrong answers. - Mismatching
left_half_sizewith the odd-case return value: Using(m + n + 1) // 2puts the extra middle element on the left (return float(left_max)), whereas(m + n) // 2puts the extra element on the right (return float(right_min)). Mixing the two is off by one element on every odd-length input. - Using integer division
// 2instead of/ 2.0for even totals: Truncates4.5down to4on[-4, 3]and[6, 11]. - Slicing arrays (
nums1[:cut1]) inside the loop: In Python, slicing copies up tomelements and turns each step intoO(m), silently ruining bothO(log(min(m, n)))time andO(1)space.
Alternative approaches
- Eliminate
k // 2elements per step (find_kthhelper): Generalize to finding thek-th smallest element (1-based) by comparingnums1[k // 2 - 1]andnums2[k // 2 - 1]and discarding the smaller prefix ofk // 2elements inO(log(m + n))time (called once for odd totals, twice for even totals). - Binary search on the numeric value: Binary-search an integer candidate
xin[-2^31, 2^31 - 1]and count how many elements across both arrays are<= xusingbisect_right. TakesO(log(value_range) * (log m + log n))(~32 outer steps), which is slightly slower for two arrays in RAM but scales naturally to many arrays across machines.
Follow-up questions
- How can you adapt the partition binary search to return the k-th smallest value (1 <= k <= m + n) across both arrays? Replace
left_half_sizewithksocut1 + cut2 == k, and clamp the search interval forcut1to[max(0, k - n), min(k, m)](sincekmight be tiny, likek = 1, or close tom + n, where an unconstrainedcut2 = k - cut1could otherwise fall outside[0, n]). Onceleft1 <= right2andleft2 <= right1hold, thek-th smallest element is simplymax(left1, left2), still inO(log(min(m, n)))time andO(1)space. - Suppose K sorted arrays live on K separate servers; how would you compute the global median while minimizing network traffic? Partitioning cuts across
Karrays simultaneously becomes multidimensional, so switch to value-space binary search: a coordinator picks a candidate valuemidbetween the global minimum and maximum, asks allKservers in parallel to count how many local elements are<= midvia local binary search (bisect_right), and sums theKcounts to decide whether to search lower or higher. For 32-bit integers, ~32 coordinator rounds find any target rank while sending only single integers over the network instead of shipping millions of array elements. - If integers arrive continuously in an unsorted stream instead of two static sorted arrays, how would you maintain the running median? Maintain two heaps: a max-heap (a binary tree array that pops its largest value in
O(log N)time, simulated in Python by negating numbers inheapq) holding the smaller half of numbers seen so far, and a min-heap (popping its smallest value inO(log N)time) holding the larger half, rebalanced so their sizes differ by at most1. Every new number inserts and rebalances inO(log N)time, and reading the current median from the heap top(s) takesO(1)time.
Follow-up questions
- How can you adapt the partition binary search to return the k-th smallest value (1 <= k <= m + n) across both arrays?
- Suppose K sorted arrays live on K separate servers; how would you compute the global median while minimizing network traffic?
- If integers arrive continuously in an unsorted stream instead of two static sorted arrays, how would you maintain the running median?
Similar questions
- Single-Pass Employee Spend Breakdowns
- Courier Trip Billing with Historical Rates
- Expense Policy Rule Evaluator
- Winning Draw Check for Incomplete Poker Hands
- Evaluating Complete and Incomplete Card Hands
- Ranking Five-Digit Card Hands with Pluggable Rules
More Rippling interview questions
- Multi-Hop Currency Conversion and Best Simple Route Easy
- Ranking Five-Digit Card Hands with Pluggable Rules Medium
- User Article Vote History Tracker Easy Pro
- In-Memory Courier Wage Ledger with Cutoff Payouts Medium Pro
- Numeric Five-Card Hand Evaluator and Partial-Hand Completions Medium Pro
- Hourly Payroll Service for Delivery Couriers Medium Pro
- Pluggable Broadcast Logger and Inverted-Index Keyword Search Easy Pro
- Global News Aggregation Platform Medium Pro
- In-Memory Delivery Cost Tracker Medium Pro
- Explicit-Preference News Feed Aggregator Medium Pro