Median of Two Sorted Arrays

The problem "Median of Two Sorted Arrays" is a classic challenge in algorithm design, often used in interviews and competitive programming. The goal is to find the median value in two sorted arrays. Understanding this problem requires a grasp of what the median is and how it can be approached in the context of two separate, sorted arrays.

Understanding the Median

The median is the middle value in an ordered list of numbers. If the list has an odd number of elements, the median is the middle element. If the list has an even number of elements, the median is the average of the two middle elements.

Problem Statement

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Constraints and Considerations

  • The overall run time complexity should be O(log(min(m,n))).
  • You may assume nums1 and nums2 cannot be both empty.


1. Merging and then Finding the Median

The simplest approach is to merge the two arrays into one sorted array and then find the median. However, this approach has a time complexity of O(m+n), which is not optimal as per the problem's constraints.

2. Binary Search (Optimal Solution)

The most efficient solution involves using binary search. Here's an outline of this approach:

  1. Binary Search on the Shorter Array: To ensure logarithmic time complexity, binary search is performed on the shorter of the two arrays. Let's say nums1 is the shorter array.

  2. Partitioning the Arrays: The idea is to partition both arrays into two halves such that:

    • The left half has as many elements as the right half (or one more if the total number of elements is odd).
    • All elements in the left halves of both arrays are less than or equal to all elements in the right halves.
  3. Finding the Correct Partition:

    • The partition in nums1 is chosen such that there are leftPartCount = (m + n + 1) / 2 elements in the left halves combined.
    • The partition in nums2 is then implicitly determined.
    • The goal is to find a partition where maxLeftNums1 ≤ minRightNums2 and maxLeftNums2 ≤ minRightNums1.
  4. Calculating the Median:

    • If m + n is odd: The median is the maximum of maxLeftNums1 and maxLeftNums2.
    • If m + n is even: The median is the average of the maximum of maxLeftNums1 and maxLeftNums2 and the minimum of minRightNums1 and minRightNums2.

Key Points

  • The problem is challenging primarily due to its requirement for a logarithmic time solution.
  • Binary search is a non-intuitive but highly efficient way to find the median without needing to merge the arrays.
  • Correctly implementing the binary search while handling edge cases (like empty partitions) is crucial for the solution.

This problem is a great example of applying binary search in a scenario that's more complex than a straightforward search in a sorted array.