Median of Two Sorted Arrays

Quick Overview

Given two sorted arrays, find their median in O(log(min(m,n))) time. A classic binary search problem that tests divide-and-conquer thinking, frequently asked at Google.

Google
Coding & Algorithms
Software Engineer
Google
Software Engineer
Onsite
Coding & Algorithms
Hard

0


Given two sorted arrays, find their median in O(log(min(m,n))) time. A classic binary search problem that tests divide-and-conquer thinking, frequently asked at Google.

Median of Two Sorted Arrays is a hard Google onsite question that separates candidates who can reason about partitions from those who only merge. The interviewer checks that you binary search on the shorter array, handle the boundary sentinels without off-by-one errors, and can prove the O(log(min(m, n))) bound.

What the Interviewer Expects
  • Explain why merging is O(m + n) and why a partition search beats it
  • Binary search the partition index in the shorter array
  • Use negative and positive infinity sentinels at partition edges
  • Handle odd and even total lengths correctly
  • Trace one example by hand, including an empty array input
Key Topics to Cover
Binary search
Array partitioning
Divide and conquer
Edge sentinels
Order statistics
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you find the k-th smallest element of two sorted arrays?
  • How does the approach generalize to k sorted arrays?
  • What if the arrays are too large for memory and live on disk?
  • Why must the search run on the shorter array?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

The problem at hand is to find the median of two sorted arrays, which can be solved efficiently using a binary search approach. The key observation is that the median divides the combined arrays into ...

Approach
  1. Identify the shorter array (let's call it A) and the longer array (B).
  2. Initialize binary search on the shorter array A.
  3. Define two pointers, left and right, to represent the curre...

Submit Your Answer
Markdown supported