kth smallest element
sorted arrays
algorithm
union of arrays
binary search

How to find the kth smallest element in the union of two sorted arrays?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding the kth smallest element in the union of two sorted arrays is a classic problem in computer science, frequently encountered in algorithms and data structures. This problem is not only fundamental but also forms the basis for more complex algorithms, such as those for merging data or finding medians. This article will guide you through understanding and solving this problem using efficient methods.

Problem Description

Given two sorted arrays A and B of size m and n respectively, the goal is to find the kth smallest element in their union. Importantly, k is a 1-based index, meaning that when k = 1, you want the smallest element, and when k = m + n, you want the largest.

Example

Input:

  • Array A: [1, 3, 5]
  • Array B: [2, 4, 6]
  • k = 4

Output:

  • The 4th smallest element in the union of A and B is 4.

Naive Approach

The simplest way to address this problem is to merge the two arrays into a single sorted array and then find the kth element. However, this approach runs in O(m+n)O(m + n) time due to the merge process, which is not optimal.

Naive Algorithm

  1. Merge arrays A and B.
  2. Sort the resulting array.
  3. Return the element at index k-1.

Although functional, this approach is inefficient for large datasets.

To optimize, a more efficient method involves the use of binary search, which reduces the time complexity to O(log(min(m,n)))O(\log(\min(m, n))). The algorithm leverages the properties of two sorted arrays to divide and conquer.

Explanation of Efficient Approach

  1. Assume m <= n. If not, swap A and B to ensure this condition.
  2. Perform a binary search on the smaller array A:
    • Set low = 0 and high = m.
    • Calculate mid = (low + high) / 2.
    • Let j = k - i.
  3. Check the partitions:
    • A[min-1] <= B[j] and B[j-1] <= A[i]
  4. Adjust your binary search based on the conditions:
    • If A[i-1] > B[j], move high to mid - 1.
    • If B[j-1] > A[i], move low to mid + 1.
  5. Once the correct partition is found, determine the element:
    • If i = 0, choose B[k-1].
    • If j = 0, choose A[k-1].
    • Otherwise, the element is max(A[i-1], B[j-1]).

Pseudocode

python
1def findKthSmallest(A, B, k):
2    if len(A) > len(B):
3        return findKthSmallest(B, A, k)
4    low, high = 0, len(A)
5
6    while low <= high:
7        i = (low + high) // 2
8        j = k - i
9
10        if i < len(A) and j > 0 and B[j-1] > A[i]:
11            low = i + 1
12        elif i > 0 and j < len(B) and A[i-1] > B[j]:
13            high = i - 1
14        else:
15            if i == 0:
16                return B[j-1]
17            if j == 0:
18                return A[i-1]
19            return max(A[i-1], B[j-1])
20    return -1

Analysis

Let's analyze the time complexity of this efficient algorithm:

  • Time Complexity: O(log(min(m,n)))O(\log(\min(m, n))), where m and n are the lengths of the two arrays.
  • Space Complexity: O(1)O(1), as no extra space is used apart from a few variables.

Edge Cases

It's important to consider the following edge cases:

  1. One Array Empty: If one array is empty, the kth element is obviously in the non-empty array.
  2. k Out of Bounds: If k is greater than m+n or less than 1, the problem is ill-posed.
  3. Equal Elements: The algorithm handles equal elements naturally due to the conditions checked.

Conclusion

Finding the kth smallest element in two sorted arrays is efficiently achievable through binary search, providing significant improvements over the naive approach. This technique is crucial for optimizing algorithms in large-scale applications and is widely applicable in other problems such as finding medians and merging sorted arrays.

Key Points Summary

ApproachTime ComplexitySpace ComplexityNotes
Naive ApproachO(m+n)O(m + n)O(m+n)O(m + n)Simple but inefficient
Binary SearchO(log(min(m,n)))O(\log(\min(m, n)))O(1)O(1)Optimal, uses binary search

Understanding and implementing the efficient algorithm can significantly enhance performance, especially in scenarios dealing with large datasets or requiring repeated queries.


Course illustration
Course illustration

All Rights Reserved.