Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Median of Two Sorted Arrays (Different Sizes)
Optimal Binary Search Approach



Problem Statement

You are given two sorted arrays that can be of different sizes. Your task is to find the median of the combined sorted array formed by merging the two arrays.

Try to solve the problem in an efficient way using binary search, with a time complexity of O(log(min(n, m)), where n and m are the lengths of the two arrays.

Examples

Array 1Array 2MedianDescription
[1, 3, 8][7, 9, 10, 11]8.0Merged array is [1, 3, 7, 8, 9, 10, 11] → median is 8 (middle element)
[1, 2][3, 4]2.5Merged: [1, 2, 3, 4] → even length → (2 + 3) / 2 = 2.5
[0, 0][0, 0]0.0All elements are 0 → median is 0
[][1]1.0Only one array has data → median is that element
[2][]2.0Only one array has data → median is that element
[][]undefinedBoth arrays are empty → no median exists
[1, 3][2]2.0Merged: [1, 2, 3] → odd length → median is 2
[1, 2, 3, 4, 5][6, 7, 8, 9, 10, 11]6.0Merged length = 11 → middle element is 6

Solution

To find the median of two sorted arrays of different sizes, we need to locate the middle value(s) of their combined sorted order—but without actually merging the arrays. Instead, we use a smart technique based on binary search to find the right partitioning between the two arrays.

What is a Median?

The median is the value that separates the lower half and upper half of a dataset. For an odd total number of elements, it's the exact middle. For an even number of elements, it's the average of the two middle values.

Key Idea

We want to split both arrays into two halves—left_half and right_half—such that:

  • The number of elements in the left half = number of elements in the right half (or one more if the total is odd)
  • The maximum of the left half ≤ the minimum of the right half

Once this condition is met, the median will either be:

  • max(left_half) if total length is odd
  • (max(left_half) + min(right_half)) / 2 if total length is even

How It Works

We apply binary search on the shorter array (for efficiency). At each step, we pick a partition index in the first array and calculate the corresponding partition in the second array to keep the total elements in left and right balanced.

We then check whether the largest element in the left part of array 1 and 2 is less than or equal to the smallest in the right part of array 1 and 2. If yes, we’ve found the correct partition.

If not, we adjust our binary search boundaries—moving left or right—until the correct split is found.

Edge Cases to Consider

  • If one array is empty, the median is simply the median of the other array.
  • If both arrays are empty, there is no median; it should return undefined or a suitable error.
  • If arrays contain duplicate values or zeros, the logic still holds since all comparisons are value-based.

Why This Approach?

Instead of merging arrays (which takes O(n + m) time), we use binary search on the smaller array, reducing time complexity to O(log(min(n, m))). This is optimal and works well even with large arrays.

This approach is powerful, elegant, and leverages the sorted nature of both arrays to avoid extra work.

Visualization

Algorithm Steps

  1. Let the two arrays be nums1 and nums2. Always apply binary search on the smaller array to minimize time.
  2. Set low = 0 and high = length of nums1.
  3. While low ≤ high, do the following:
  4. → Compute partitionX = (low + high) / 2.
  5. → Compute partitionY = (n + m + 1)/2 - partitionX.
  6. → Find maxLeftX, minRightX, maxLeftY, and minRightY using partition indices.
  7. → If maxLeftX ≤ minRightY and maxLeftY ≤ minRightX, you found the correct partition.
  8. → Compute median depending on even/odd total length.
  9. If not, adjust low or high accordingly.
  10. If no partition is found, return 0 (edge case safety).

Code

Python
Java
C++
JavaScript
C
C#
Kotlin
Swift
Go
Php
def findMedianSortedArrays(nums1, nums2):
    if len(nums1) > len(nums2):
        nums1, nums2 = nums2, nums1

    x, y = len(nums1), len(nums2)
    low, high = 0, x

    while low <= high:
        partitionX = (low + high) // 2
        partitionY = (x + y + 1) // 2 - partitionX

        maxLeftX = float('-inf') if partitionX == 0 else nums1[partitionX - 1]
        minRightX = float('inf') if partitionX == x else nums1[partitionX]

        maxLeftY = float('-inf') if partitionY == 0 else nums2[partitionY - 1]
        minRightY = float('inf') if partitionY == y else nums2[partitionY]

        if maxLeftX <= minRightY and maxLeftY <= minRightX:
            if (x + y) % 2 == 0:
                return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2.0
            else:
                return max(maxLeftX, maxLeftY)
        elif maxLeftX > minRightY:
            high = partitionX - 1
        else:
            low = partitionX + 1

    return 0.0

print(findMedianSortedArrays([1, 3], [2]))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)Median found on the first partition guess if the arrays are perfectly balanced.
Average CaseO(log(min(n, m)))Binary search on the smaller array ensures logarithmic steps for finding the correct partition.
Average CaseO(log(min(n, m)))In worst case, binary search continues until all elements in the smaller array are checked.

Space Complexity

O(1)

Explanation: Only a fixed number of variables are used for partitioning logic. No extra space is required.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M