⬅ Previous Topic
Median of Two Sorted Arrays of Different SizesNext Topic ⮕
Reverse Words in a String⬅ Previous Topic
Median of Two Sorted Arrays of Different SizesNext Topic ⮕
Reverse Words in a StringTopic Contents
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
.
arr1
be the smaller array among the two. If not, swap arr1
and arr2
.n = arr1.length
and m = arr2.length
.cut1 = (low + high) / 2
, cut2 = k - cut1
.l1 = -∞
if cut1 == 0
, else arr1[cut1 - 1]
.l2 = -∞
if cut2 == 0
, else arr2[cut2 - 1]
.r1 = ∞
if cut1 == n
, else arr1[cut1]
.r2 = ∞
if cut2 == m
, else arr2[cut2]
.l1 ≤ r2
and l2 ≤ r1
, return max(l1, l2)
.l1 > r2
, move left: high = cut1 - 1
.low = cut1 + 1
.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | If the correct partition is found in the first attempt. |
Average Case | O(log(min(n, m))) | Binary search runs on the smaller array, halving the search space at each step. |
Average Case | O(log(min(n, m))) | The binary search continues until all partition points are exhausted on the smaller array. |
O(1)
Explanation: Only a constant amount of additional variables are used for computation and control.
⬅ Previous Topic
Median of Two Sorted Arrays of Different SizesNext Topic ⮕
Reverse Words in a StringYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.