Skip to main content

Median of Two Sorted Arrays

Given two sorted arrays nums1 and nums2 Return the median of the combined sorted arrays Must use O(log(m+n)) time complexity Example: nums1 = [1,3], nums2 = [2] => 2.0 Example: nums1 = [1,2], nums2 = [3,4] => 2.5

Binary search on the smaller array to find the partition point where left half elements all <= right half elements in both arrays - handle edge cases with infinity. O(log(min(m,n))) and a brutal problem that tests binary search mastery; understanding the invariant is half the battle.

Examples

You write

find_median_sorted_arrays(nums1: List[int], nums2: List[int])

  1. Example 1

    Input
    nums1 = [1,3], nums2 = [2]
    returns
    2.0
  2. Example 2

    Input
    nums1 = [1,2], nums2 = [3,4]
    returns
    2.5

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Binary Search

I reach for it when

  • The input is sorted, or sorted and then rotated.
  • You want a boundary: the first or last place something is true.

Say this before you type. Say the yes-or-no question, and which side each answer throws away.

All 19 Binary Search problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Find Median of Two Sorted Arrayshard

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.