Taro Logo

Median of Two Sorted Arrays

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+33
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.8K views
Topics:
ArraysBinary Search

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)).

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 == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -106 <= nums1[i], nums2[i] <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if both input arrays are completely empty?
  2. Can the two input arrays be of different lengths, and could one of them be significantly larger than the other?
  3. What are the data types of the elements inside the arrays (e.g., standard integers, floating-point numbers), and what is the expected range of these values?
  4. Are duplicate values allowed within the input arrays, and if so, how should they be handled when computing the median?
  5. Is the combined collection guaranteed to be non-empty before we attempt to calculate the median?

Brute Force Solution

Approach

Imagine you have two separate groups of items, both already arranged in order from smallest to largest, and you want to find the exact middle value. The brute force approach involves gathering everything into one single giant pile, sorting the entire combined pile from scratch, and then locating the item sitting right in the middle.

Here's how the algorithm would work step-by-step:

  1. Take every single item from the first group and place it into a brand new, empty workspace.
  2. Take every single item from the second group and add them all to that exact same workspace so everything is mixed together.
  3. Sort the entire collection in the workspace so that every single item is now in strict order from smallest to largest.
  4. Count how many total items you have gathered in your workspace.
  5. If you have an odd total count, point directly to the single item sitting right in the exact middle of the sorted collection.
  6. If you have an even total count, look at the two items sitting side by side in the middle.
  7. Find the halfway point between those two middle items by adding their values together and dividing the result by two.

Code Implementation

class Solution:
    def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
        combined_workspace = []

        # Combine both sorted groups into a single workspace to prepare for sorting all elements together
        for current_number in nums1:
            combined_workspace.append(current_number)

        for current_number in nums2:
            combined_workspace.append(current_number)

        # Sort the entire collection so that every single item is now in strict order from smallest to largest
        combined_workspace.sort()

        total_items_count = len(combined_workspace)
        middle_index = total_items_count // 2

        # Check if the total count is odd to locate the single median item directly in the middle
        if total_items_count % 2 != 0:
            return float(combined_workspace[middle_index])

        # If the count is even, average the two middle items to find the exact halfway point
        first_middle_item = combined_workspace[middle_index - 1]
        second_middle_item = combined_workspace[middle_index]
        return (first_middle_item + second_middle_item) / 2.0

Big(O) Analysis

Time Complexity
O((m + n) log(m + n)) – The brute force approach requires taking all elements from both sorted groups, where let m be the size of the first group and n be the size of the second group, and placing them into a single workspace. Gathering all elements takes linear time proportional to the total number of items, which is (m + n). Sorting this combined collection of (m + n) elements dominates the cost using standard comparison sorting algorithms. This results in approximately (m + n) * log(m + n) total operations, which simplifies to the overall Big O time complexity of O((m + n) log(m + n)).
Space Complexity
O(N) – The brute force approach requires a brand new, empty workspace to gather and combine every single item from both input groups. If we define N as the total number of elements across both sorted arrays, this temporary collection must hold all N elements simultaneously. Consequently, this auxiliary data structure grows linearly with the input size, dominating the extra memory usage. Simplifying this linear storage requirement gives a final space complexity of O(N).

Optimal Solution

Approach

Instead of combining everything into one giant sorted list, the optimal approach treats the problem like balancing two stacked shelves of items by weight. By cleverly adjusting how much of each shelf we look at, we can quickly pinpoint the exact middle point without having to look at every single item.

Here's how the algorithm would work step-by-step:

  1. Imagine you have two collections of sorted items, one shorter and one longer.
  2. Your goal is to cut both collections into two halves so that everything in the left halves is smaller than everything in the right halves, and both left halves together contain exactly half of all the items.
  3. To do this, start by guessing a split point on the shorter collection.
  4. Use that guess to automatically figure out where the split point on the longer collection must be to keep the total count on both sides balanced.
  5. Check if your split is correct by looking at the items right around the cut. Specifically, make sure the biggest item on the left is smaller than or equal to the smallest item on the right for both collections.
  6. If the items are out of order, it means you took too many items from one collection and not enough from the other. Adjust your guess on the shorter collection accordingly.
  7. Repeat this adjustment process until the items line up perfectly.
  8. Once the perfect split is found, look at the items right at the boundary to calculate the middle value, handling whether the total number of items is even or odd.

Code Implementation

class Solution:
    def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1
            
        total_length = len(nums1) + len(nums2)
        half_length = total_length // 2
        min_index = 0
        max_index = len(nums1)
        
        # We binary search the smaller array to find the correct partition point.
        while min_index <= max_index:
            partition_one = (min_index + max_index) // 2
            partition_two = half_length - partition_one
            
            left_one = float('-inf') if partition_one == 0 else nums1[partition_one - 1]
            right_one = float('inf') if partition_one == len(nums1) else nums1[partition_one]
            
            left_two = float('-inf') if partition_two == 0 else nums2[partition_two - 1]
            right_two = float('inf') if partition_two == len(nums2) else nums2[partition_two]
            
            # We check if left partitions are smaller than right partitions to validate the cut.
            if left_one <= right_two and left_two <= right_one:
                if total_length % 2 == 0:
                    return (max(left_one, left_two) + min(right_one, right_two)) / 2.0
                else:
                    return float(min(right_one, right_two))
            elif left_one > right_two:
                max_index = partition_one - 1
            else:
                min_index = partition_one + 1

Big(O) Analysis

Time Complexity
O(log(min(m, n))) – Instead of scanning all elements, the algorithm performs a binary search strictly on the shorter collection whose length we can call min(m, n). With each step of this search, the partitioning range of that shorter collection is halved to locate the correct split point. This narrowing process mirrors standard binary search behavior, meaning the number of steps grows logarithmically relative to the size of the smaller input. Therefore, the operations scale roughly as log base 2 of min(m, n), which simplifies to O(log(min(m, n))).
Space Complexity
O(1) – The optimal binary search approach on the shorter collection uses only a few primitive pointer and index variables to track our guess and boundaries. Because we never combine the collections into a giant sorted list or allocate temporary arrays, no extra memory scales with the input size N. Therefore, the auxiliary space complexity remains strictly constant regardless of the total number of elements across both collections.

Edge Cases

One or both input arrays are completely empty
How to Handle:
Binary search partition logic safely handles empty arrays by treating them as having zero elements on that side.
Arrays of minimum size such as one element in each array
How to Handle:
The partition bounds properly adjust to calculate the median using the single elements from both arrays.
Combined total number of elements is odd versus even
How to Handle:
The algorithm checks the parity of the total length to return either the single middle element or the average of the two middle elements.
All elements in one array are smaller than all elements in the other array
How to Handle:
Binary search correctly shifts the partition all the way to the left or right edge of the larger array.
Arrays contain highly skewed distributions with duplicate or identical values
How to Handle:
Relies on relative ordering through binary search rather than distinct value counts, maintaining correct partition logic.
Inputs contain negative numbers, zeros, and extreme boundary values
How to Handle:
Comparison operators handle signed numbers natively without requiring offset transformations or data normalization.
Maximum-sized input arrays pushing performance limits
How to Handle:
Achieves strict logarithmic time complexity O(log(min(m, n))) by performing binary search only on the smaller array.
Floating point precision issues when calculating the median of two middle integers
How to Handle:
Casts integer values to floating-point numbers before division to prevent integer truncation and maintain precision.
0/75 completed