Neural Mastery
← Practice
Median of Two Sorted Arrayshard

Median of Two Sorted Arrays

hard Coding Interview Patterns 25–30 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement the binary-search-on-partition-point solution to Median of Two Sorted Arrays -- one of the most-cited "hard" interview problems, solved by binary searching for a partition rather than ever merging the arrays.

Related Skills

Task

Implement find_median_sorted_arrays(nums1, nums2): binary search over the SHORTER array for a partition index i (with the other array's partition j determined by i, so the left halves together hold exactly half the total elements), such that every element left of the partition is <= every element right of it. The median is then derived directly from the four boundary values around that partition.

Function Signature

find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float

Examples

Example 1: Odd Total Length
Input: nums1 = [1, 3] nums2 = [2]
Output: 2
Example 2: Even Total Length
Input: nums1 = [1, 2] nums2 = [3, 4]
Output: 2.5

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must run in O(log(min(m, n))) time -- binary search over the shorter array, never merge the two arrays.
  • Return a float even when the answer is a whole number (e.g. 2.0, not 2).
  • One of the two input arrays may be empty; the other is never empty at the same time.
Python3Saved ✓
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""nums1 and nums2 are each already sorted ascending. Return the
median of the combined (conceptually merged) sorted array, as a
float, in O(log(min(len(nums1), len(nums2)))) time -- do not
actually merge the two arrays."""
# Your implementation here
pass

Case 1: Odd Total Length
Input: nums1 = [1, 3] nums2 = [2]
Expected: 2
Case 2: Even Total Length
Input: nums1 = [1, 2] nums2 = [3, 4]
Expected: 2.5