Grok 4.1 Fast· xai
Frontier Reasoning Traces
Design an algorithm to find the median of two sorted arrays in O(log n) time.
- User
Design an algorithm to find the median of two sorted arrays in O(log n) time.
- Assistant
Algorithm to Find Median of Two Sorted Arrays in O(log min(m, n)) Time
Problem Overview
- Given two sorted arrays
A(lengthm) andB(lengthn), find the median of the combined sorted array. - Median definition:
- If
m + nis odd: The middle element. - If
m + nis even: Average of the two middle elements.
- If
- Goal: Achieve O(log min(m, n)) time complexity using binary search (no merging required).
Key Insight: Binary Search on Partitions
- We don't merge the arrays. Instead, we partition them into left and right halves such that:
- The left half contains exactly
(m + n + 1) // 2elements (handles both odd/even cases elegantly). - All elements in left ≤ all elements in right, i.e.,
max(left) ≤ min(right).
- The left half contains exactly
- Binary search on the partition point
iin the smaller array (assumem ≤ n; swap if needed).i= # elements fromAin left half (ranges 0 tom).j=(m + n + 1) // 2 - i(# elements fromBin left half).
- For a candidate
(i, j):- Check:
A[i-1] ≤ B[j]andB[j-1] ≤ A[i]. - Use
±∞for boundary cases (e.g.,i=0means noA[i-1]).
- Check:
- Adjust search:
- If
A[i-1] > B[j]: Too many large elements fromA→ decreasei. - If
B[j-1] > A[i]: Too few fromA→ increasei.
- If
Why O(log min(m, n))?
- Binary search over
m(smaller array): O(log m) iterations. - Each iteration: O(1) time (constant-time checks).
Pseudocode
def findMedianSortedArrays(A, B): # Ensure A is the smaller array if len(A) > len(B): A, B = B, A m, n = len(A), len(B) low, high = 0, m while low <= high: i = (low + high) // 2 # Partition in A j = (m + n + 1) // 2 - i # Partition in B # Handle boundaries with infinities leftA = float('-inf') if i == 0 else A[i-1] rightA = float('inf') if i == m else A[i] leftB = float('-inf') if j == 0 else B[j-1] rightB = float('inf') if j == n else B[j] # Valid partition? if leftA <= rightB and leftB <= rightA: # Compute median if (m + n) % 2 == 1: # Odd total return max(leftA, leftB) else: # Even total return (max(leftA, leftB) + min(rightA, rightB)) / 2.0 elif leftA > rightB: high = i - 1 # Move left in A else: # leftB > rightA low = i + 1 # Should not reach here if inputs are valid sorted arrays raise ValueError("Input arrays must be sorted")Example Walkthrough
Input:
A = [1, 3],B = [2](m=2, n=1 → swap to A=[2], B=[1,3]; total=3, odd)- low=0, high=1
- i=0, j=2-0=2 → leftA=-∞, rightA=2, leftB=3, rightB=∞ → -∞≤∞ (true), 3≤2 (false) → low=1
- i=1, j=2-1=1 → leftA=2, rightA=∞, leftB=1, rightB=3 → 2≤3 (true), 1≤∞ (true) → valid
- Odd: max(2,1) = 2 ✓ (combined: [1,2,3] median=2)
Input:
A = [1, 3],B = [2, 4](m=2,n=2, even)- i=1, j=2 → leftA=1,rightA=3,leftB=2,rightB=4 → 1≤4,2≤3 ✓
- Even: (max(1,2) + min(3,4))/2 = (2+3)/2 = 2.5 ✓ (combined: [1,2,3,4])
Edge Cases Handled
- One empty array: e.g.,
A=[], B=[1,2,3]→ median=2. - All elements equal: Works (any valid partition).
m=1, n=1: Correctly handles.- Large inputs: Efficient (no full scan).
Proof Sketch (Correctness)
- Invariant: Binary search converges to valid
(i,j)because partition conditions are monotonic. (m+n+1)//2ensures left has the "upper median" position.
This is the optimal linearithmic solution (better than merge-based O(m+n)). Implement in any language with minor index adjustments!
- Given two sorted arrays
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.