Skip to main content

Median of Two Sorted Arrays(Leetcode)

In this page, we will solve the problem Median of Two Sorted Arrays from LeetCode. We will provide multiple approaches to solve the problem along with the code implementation and the complexity analysis of the code.

Problem Statement

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

The overall run time complexity should be O(log(m+n))O(log (m+n)).

Example 1

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

Example 2

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Constraints:

  • nums1.length==mnums1.length == m
  • nums2.length==nnums2.length == n
  • 0<=m<=10000 <= m <= 1000
  • 0<=n<=10000 <= n <= 1000
  • 1<=m+n<=20001 <= m + n <= 2000
  • 106<=nums1[i],nums2[i]<=106-10^6 <= nums1[i], nums2[i] <= 10^6

Solution for Median of Two Sorted Arrays

The Median of Two Sorted Arrays is a classic algorithm problem on LeetCode (Problem 4). It requires finding the median of two sorted arrays. Given two sorted arrays nums1 and nums2, the task is to find the median of the two arrays combined.

Here is an explanation of the intuition and approaches to solve this problem:

intuition

The median is the middle value of a dataset. For an even number of elements, it is the average of the two middle values. If we have two sorted arrays, the naive approach would involve merging both arrays and then finding the median, but this approach does not take full advantage of the fact that the arrays are already sorted and is not efficient for large arrays.

Instead, we can use a more advanced approach to find the median in O(log(min(n,m)))O(log(min(n, m))) time, where n and m are the lengths of the two arrays. This involves using a binary search method. The idea is to partition both arrays into two halves such that the combined left half and right half are both sorted and of equal length (or differing by one).

The binary search approach involves partitioning the two arrays such that the combined left half and right half are both sorted and of equal length (or differing by one). We can then find the median based on these partitions.

Pseudocode

  1. Ensure nums1 is the smaller array.
  2. Initialize low and high for binary search on nums1.
  3. While low <= high:
    • Calculate partitionX and partitionY.
    • Set maxX, minX, maxY, minY.
    • If maxX <= minY and maxY <= minX:
      • If total number of elements is even
        • Return average of max(maxX, maxY) and min(minX, minY).
      • Else
        • Return max(maxX, maxY).
    • If maxX > minY:
      • Move high to partitionX - 1.
    • Else:
      • Move low to partitionX + 1.
  4. If no median is found, raise an error.

Implementation and Code

Here is a live code editor for you to play around with the solution:

Live Editor
function medianOfTwoSortedArraysProblem() {
  const findMedianSortedArrays = (nums1, nums2) => {
    // Ensure nums1 is the smaller array
    if (nums1.length > nums2.length) {
      [nums1, nums2] = [nums2, nums1];
    }
    
    const x = nums1.length;
    const y = nums2.length;
    let low = 0, high = x;
    
    while (low <= high) {
      const partitionX = Math.floor((low + high) / 2);
      const partitionY = Math.floor((x + y + 1) / 2) - partitionX;
      
      const maxX = (partitionX === 0) ? -Infinity : nums1[partitionX - 1];
      const minX = (partitionX === x) ? Infinity : nums1[partitionX];
      
      const maxY = (partitionY === 0) ? -Infinity : nums2[partitionY - 1];
      const minY = (partitionY === y) ? Infinity : nums2[partitionY];
      
      if (maxX <= minY && maxY <= minX) {
        if ((x + y) % 2 === 0) {
          return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;
        } else {
          return Math.max(maxX, maxY);
        }
      } else if (maxX > minY) {
        high = partitionX - 1;
      } else {
        low = partitionX + 1;
      }
    }
    
    throw new Error("Input arrays are not sorted.");
  };

  const nums1 = [1, 3];
  const nums2 = [2];
  const result = findMedianSortedArrays(nums1, nums2);

  return (
    <div>
      <p>
        <b>Input:</b> nums1 = {"[" + nums1.join(", ") + "]"}, nums2 = {"[" + nums2.join(", ") + "]"}
      </p>
      <p>
        <b>Output:</b> {result}
      </p>
    </div>
  );
}
Result
Loading...

Code in Different Languages

Written by @ajay-dhangar
var findMedianSortedArrays = function(nums1, nums2) {
if (nums1.length > nums2.length) {
[nums1, nums2] = [nums2, nums1];
}

let x = nums1.length;
let y = nums2.length;
let low = 0, high = x;

while (low <= high) {
let partitionX = Math.floor((low + high) / 2);
let partitionY = Math.floor((x + y + 1) / 2) - partitionX;

let maxX = (partitionX === 0) ? -Infinity : nums1[partitionX - 1];
let minX = (partitionX === x) ? Infinity : nums1[partitionX];

let maxY = (partitionY === 0) ? -Infinity : nums2[partitionY - 1];
let minY = (partitionY === y) ? Infinity : nums2[partitionY];

if (maxX <= minY && maxY <= minX) {
if ((x + y) % 2 === 0) {
return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;
} else {
return Math.max(maxX, maxY);
}
} else if (maxX > minY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
}

throw new Error("Input arrays are not sorted.");
};

Complexity Analysis

  • Time Complexity: The time complexity of this approach is O(log(min(n,m)))O(log(min(n, m))), where n and m are the lengths of the two arrays. The binary search approach helps in reducing the search space and finding the median efficiently.
  • Space Complexity: The space complexity of this approach is O(1)O(1) as we are using constant extra space.

Test Cases

Let's test the solution with the sample test cases:

Input: nums1 = [1, 3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1, 2, 3] and median is 2.
info

Note: The binary search approach is more efficient than the divide and conquer approach as it has a better time complexity of O(log(min(n,m)))O(log(min(n, m))) compared to the divide and conquer approach. However, both approaches provide a solution to the problem of finding the median of two sorted arrays.

Which approach is best for you?

The binary search approach is more efficient and recommended for solving the problem of finding the median of two sorted arrays. However, the divide and conquer approach is also a valid solution and can be used if needed.

tip

When asked to find the median of two sorted arrays, a direct approach that merges the two arrays and then finds the median will work but isn't optimal. Given the problem's constraints, we can leverage the fact that the arrays are already sorted and use binary search to find the median in O(log(min(n,m)))O(\log(\min(n, m))) time complexity.

The key idea is to use binary search to partition the smaller array in such a way that we can easily find the median by comparing elements around the partition.

Detailed Explanation

  1. Ensure the Smaller Array is First:

    • This step is to make sure we always perform the binary search on the smaller array, which helps us manage the partition logic more easily. Let nums1\text{nums1} be the smaller array and nums2\text{nums2} be the larger array.
  2. Set Up Binary Search:

    • Initialize low\text{low} and high\text{high} pointers for the binary search on nums1\text{nums1}.
    • We aim to partition nums1\text{nums1} and nums2\text{nums2} such that the left side of the combined arrays contains half of the elements, and the right side contains the other half.
  3. Partitioning the Arrays:

    • Calculate partitionX\text{partitionX} as the midpoint of nums1\text{nums1}.

    • Calculate partitionY\text{partitionY} such that the left side of the combined arrays has the same number of elements as the right side. This can be achieved by:

      partitionY=(x+y+1)2partitionX\text{partitionY} = \frac{(x + y + 1)}{2} - \text{partitionX}

      where xx and yy are the lengths of nums1\text{nums1} and nums2\text{nums2} respectively.

  4. Boundary Conditions:

    • Handle cases where partitions might go out of bounds. If partitionX\text{partitionX} is 0, it means there are no elements on the left side of nums1\text{nums1}. If partitionX\text{partitionX} is xx, it means there are no elements on the right side of nums1\text{nums1}.
  5. Check Valid Partition:

    • A valid partition is one where the maximum element on the left side of both partitions is less than or equal to the minimum element on the right side of both partitions: maxXminYandmaxYminX\text{maxX} \leq \text{minY} \quad \text{and} \quad \text{maxY} \leq \text{minX} Here, maxX\text{maxX} is the largest element on the left side of nums1\text{nums1}, minX\text{minX} is the smallest element on the right side of nums1\text{nums1}, and similarly for nums2\text{nums2}.
  6. Calculate the Median:

    • If the total number of elements (x+y)(x + y) is even, the median is the average of the two middle values: median=max(maxX, maxY)+min(minX, minY)2\text{median} = \frac{\text{max(maxX, maxY)} + \text{min(minX, minY)}}{2}
    • If the total number of elements is odd, the median is the maximum element of the left partition: median=max(maxX, maxY)\text{median} = \text{max(maxX, maxY)}
  7. Adjust Binary Search:

    • If maxX>minY\text{maxX} > \text{minY}, it means we need to move the partition in nums1\text{nums1} to the left, so adjust high\text{high}.
    • If maxY>minX\text{maxY} > \text{minX}, it means we need to move the partition in nums1\text{nums1} to the right, so adjust low\text{low}.

Authors:

Loading...