AlgoMaster Logo

Median of Two Sorted Arrays

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

The simplest approach to find the median of two sorted arrays is to merge them into a single sorted array, then directly find the median. This approach leverages the idea of merging two arrays, similar to the merge process in merge sort.

Steps:

  1. Initialize an array to hold the merged elements of the two input arrays.
  2. Use two pointers to iterate over both arrays and append the smaller element from the two into the merged array.
  3. If one array is exhausted, append the remaining elements of the other array.
  4. Calculate the median from the merged array:
    • If the size of the merged array is odd, the median is the middle element.
    • If the size is even, the median is the average of the two middle elements.

Code:

2. Optimized Binary Search Approach

Intuition:

A more efficient approach uses binary search. Instead of merging the entire arrays, we use binary search on the shorter array to partition the two arrays into two halves such that all elements on the left side are less than or equal to all elements on the right side. This way, we can determine the median in O(log(min(m, n))) time.

Steps:

  1. Make sure to always use binary search on the smaller array to minimize the time complexity.
  2. Use binary search to find the correct partition:
    • Divide both arrays into two halves such that the maximum element on the left is less than or equal to the minimum element on the right from both arrays.
  3. Once the correct partition is found:
    • If the combined length of arrays is even, the median is the average of the maximum element of the left part and the minimum element of the right part.
    • If it's odd, the median is the maximum element of the left part.

Code: