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 K-th Element of Two Sorted Arrays
Optimal Binary Search Approach



Problem Statement

Given two sorted arrays arr1 and arr2, and a number k, your task is to find the K-th smallest element in the merged array formed by combining both arrays.

If either array is empty, the answer will depend entirely on the other array. If k is invalid (e.g., larger than total elements), return -1.

Examples

Array 1Array 2kOutputDescription
[2, 3, 6, 7, 9][1, 4, 8, 10]54Combined sorted array: [1,2,3,4,6,...], 5th element is 4
[1, 2, 3][4, 5, 6]44Combined: [1,2,3,4,5,6], 4th element is 4
[1, 2][3, 4, 5, 6]666th smallest element overall
[1, 2, 3, 4][]22Only one array present, pick 2nd element
[][5, 10, 15]315Only one array present, pick 3rd element
[][5, 10, 15]4-1k = 4 is out of range (array size = 3)
[][]1-1Both arrays are empty
[1][2]22Combined: [1, 2], 2nd element is 2

Solution

To find the K-th smallest element in the union of two sorted arrays, we don't need to fully merge them. Instead, we use a binary search approach that narrows down the possible range efficiently.

Understanding the Problem

Imagine merging both arrays and sorting them. The K-th smallest element is simply the element at index k - 1 in this combined array. But instead of merging, we want to simulate this merging process using binary search on partitions.

General Strategy

We perform binary search on the smaller array to decide how many elements to take from it. Let’s say we take cut1 elements from arr1, then we take k - cut1 elements from arr2. The idea is to make sure all elements on the left side of the partition are less than or equal to all elements on the right side.

Different Scenarios

  • Normal Case: Both arrays are non-empty. We can find the correct partition by comparing the left and right elements around the cut. The answer will be the maximum of the left halves of the partitions.
  • Empty Array Case: If one array is empty, then the answer is simply the K-th element of the other array. For example, if arr1 = [] and arr2 = [10, 20, 30], then the 2nd element is 20.
  • Out-of-Bounds K: If k is more than the total number of elements in both arrays, it’s invalid. In that case, we return -1 to indicate no such K-th element exists.
  • Equal Lengths / Unbalanced Lengths: The algorithm works regardless of how balanced or unbalanced the array sizes are. It always searches in the smaller array to keep time complexity minimal.

Why Binary Search Works Here

Binary search reduces the number of comparisons by cutting the search space in half on every step. This makes the approach very efficient with a time complexity of O(log(min(n, m))), where n and m are the sizes of the two arrays.

This is much faster than merging the arrays, which takes O(n + m) time and uses additional space. So this binary search approach is both time-efficient and space-efficient.

Visualization

Algorithm Steps

  1. Let arr1 be the smaller array among the two. If not, swap arr1 and arr2.
  2. Let n = arr1.length and m = arr2.length.
  3. Set low = max(0, k - m) and high = min(k, n).
  4. While low ≤ high, do:
  5. → Set cut1 = (low + high) / 2, cut2 = k - cut1.
  6. → Use l1 = -∞ if cut1 == 0, else arr1[cut1 - 1].
  7. → Use l2 = -∞ if cut2 == 0, else arr2[cut2 - 1].
  8. → Use r1 = ∞ if cut1 == n, else arr1[cut1].
  9. → Use r2 = ∞ if cut2 == m, else arr2[cut2].
  10. If l1 ≤ r2 and l2 ≤ r1, return max(l1, l2).
  11. Else if l1 > r2, move left: high = cut1 - 1.
  12. Else, move right: low = cut1 + 1.

Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Php
def find_kth_element(arr1, arr2, k):
    n, m = len(arr1), len(arr2)
    if n > m:
        return find_kth_element(arr2, arr1, k)

    low, high = max(0, k - m), min(k, n)
    while low <= high:
        cut1 = (low + high) // 2
        cut2 = k - cut1

        l1 = float('-inf') if cut1 == 0 else arr1[cut1 - 1]
        l2 = float('-inf') if cut2 == 0 else arr2[cut2 - 1]
        r1 = float('inf') if cut1 == n else arr1[cut1]
        r2 = float('inf') if cut2 == m else arr2[cut2]

        if l1 <= r2 and l2 <= r1:
            return max(l1, l2)  # Found the kth element
        elif l1 > r2:
            high = cut1 - 1  # Move left in arr1
        else:
            low = cut1 + 1   # Move right in arr1
    return -1

# Sample Input
arr1 = [2, 3, 6, 7, 9]
arr2 = [1, 4, 8, 10]
k = 5
print("K-th element:", find_kth_element(arr1, arr2, k))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)If the correct partition is found in the first attempt.
Average CaseO(log(min(n, m)))Binary search runs on the smaller array, halving the search space at each step.
Average CaseO(log(min(n, m)))The binary search continues until all partition points are exhausted on the smaller array.

Space Complexity

O(1)

Explanation: Only a constant amount of additional variables are used for computation and control.



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