Kth Element in Union of Two Sorted Lists
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Tests ability to find the kth smallest element from two sorted arrays using binary search on partition counts rather than merging.
You are given two sorted arrays of integers (in nondecreasing order) and an integer k (1-indexed). Your task is to determine the kth smallest element when considering both arrays together as a single collection. Duplicate values are counted as separate elements.
Your solution must not merge the arrays into a single structure.
Write a function that takes two sorted integer arrays and a position k, then returns the element that would be at position k if all elements were sorted together.
Constraints
- Each array has length between 0 and 200,000
- At least one array is nonempty
1 <= k <= len(nums1) + len(nums2)- Array elements are integers in the range [-10^9, 10^9]
- Both input arrays are sorted in nondecreasing order
- Your solution should use O(1) extra space and O(log(min(m, n))) time complexity
Examples
Example 1
Input: find_kth_element([1, 3, 7], [2, 2, 9], 4)
Output: 3
Example 2
Input: find_kth_element([], [5], 1)
Output: 5
Hints
Hint 1
Consider how many elements from each array should be included in the first k elements overall.
Hint 2
Binary search can be applied to the count of elements taken from one array, with the other count determined by subtraction.
Hint 3
Use sentinel values (infinity and negative infinity) to handle boundary cases where all or none of an array is included.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that the k smallest elements from both arrays combined must consist of some prefix from the first array and some prefix from the second array. Instead of merging and sorting, we can binary search on how many elements to take from one array, which automatically determines how many to take from the other.
If we select count1 elements from nums1, we must select exactly k - count1 elements from nums2 to have k elements total. The question becomes: what is the correct value of count1?
For a partition to be valid, every element we include must be less than or equal to every element we exclude. Since each array is already sorted, this is automatically true within each array. We only need to check the cross-boundaries:
- The last included element from
nums1must be ≤ the first excluded element fromnums2 - The last included element from
nums2must be ≤ the first excluded element fromnums1
We use binary search on the count taken from the shorter array (swapping if necessary). For boundary cases where we take all or none from an array, we use negative and positive infinity as sentinels.
The search range for count1 is constrained by:
- Lower bound:
max(0, k - n)ensurescount2 = k - count1doesn't exceed the length ofnums2 - Upper bound:
min(k, m)ensurescount1doesn't exceed the length ofnums1
When both cross-boundary conditions are satisfied, the kth element is the maximum of the two last included elements (one from each array).
Correctness
A valid partition always exists because if we were to actually merge the arrays, the first k elements would naturally form such a partition. The binary search is guaranteed to find it because:
- If we take too many from
nums1, the last element taken fromnums1will exceed the first excluded element fromnums2, indicating we should decrease our count - If we take too few from
nums1, the symmetric violation occurs withnums2 - These conditions are monotonic in the count, making binary search applicable
The result is always a real integer (never a sentinel) because k >= 1 guarantees at least one element is taken from one of the arrays.
Complexity
- Time: O(log(min(m, n))) where m and n are the array lengths. We binary search over the shorter array with constant work per iteration.
- Space: O(1) extra space. We only use a fixed number of variables; swapping references doesn't copy data.
Solution
from typing import List
def find_kth_element(nums1: List[int], nums2: List[int], k: int) -> int:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
lo = max(0, k - n)
hi = min(k, m)
while lo <= hi:
take_a = (lo + hi) // 2
take_b = k - take_a
left_a = nums1[take_a - 1] if take_a else float('-inf')
right_a = nums1[take_a] if take_a < m else float('inf')
left_b = nums2[take_b - 1] if take_b else float('-inf')
right_b = nums2[take_b] if take_b < n else float('inf')
if left_a > right_b:
hi = take_a - 1
elif left_b > right_a:
lo = take_a + 1
else:
return max(left_a, left_b)
raise ValueError('invalid arguments')