Kth Biggest Value Across a Pair of Ascending Lists
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Find the kth largest value in the union of two ascending integer lists, counting duplicates, ideally using binary search on a partition instead of a full merge.
You are given two integer lists, first and second, each sorted in non-decreasing (ascending) order, and a positive integer k.
Imagine pooling every element from both lists into one collection and sorting it from largest to smallest. Return the value at position k in that ordering, where position 1 is the largest value.
Rules:
- Repeated values each count as their own element. For instance, if the pooled values are
5, 5, then the 1st and 2nd largest are both5. - Either list may be empty, but together they hold at least
kelements. - Return the value itself (an integer), not its index.
A simple merge that walks k steps works, but a stronger solution uses the sorted order to run in roughly O(log(min(m, n))) time, where m and n are the list lengths.
Constraints
firstandsecondare sorted in non-decreasing order.0 <= len(first), len(second)andlen(first) + len(second) >= 1.1 <= k <= len(first) + len(second).- Elements are integers and may be negative or repeated.
Examples
Example 1
Input: kth_largest_two_sorted([0, 1, 4, 5, 6, 7, 8, 10, 13], [1, 3, 4, 5, 8, 9, 11, 12], 3)
Output: 11
Hints
Hint 1
Turn the question around: the kth largest of N total elements is the (N - k + 1)th smallest. Work out this rank carefully to avoid an off-by-one.
Hint 2
The `rank` smallest elements consist of a prefix of one list plus a prefix of the other. If you decide how many to take from the shorter list, the count from the other list is determined.
Hint 3
Binary search on the prefix length taken from the shorter list. A split is valid when the last taken element of each list is no larger than the first untaken element of the other list. Use negative and positive infinity for missing neighbors, and the answer is the larger of the two last-taken elements.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let m and n be the list lengths. The kth largest of the combined m + n elements is the rankth smallest, where rank = m + n - k + 1.
The rank smallest elements form some prefix of the first list (length i) and some prefix of the second list (length j), with i + j = rank. Choosing i fixes j, so we only need to search over one integer.
Around a cut, look at four neighbors: the last taken and first untaken element of each list (using -inf / +inf when the cut sits at an end). The cut is valid when
a_left <= b_right and b_left <= a_right
(each list is already sorted, so these two cross-checks are enough). For a valid cut, the left side is exactly the rank smallest elements, and the answer is max(a_left, b_left).
We binary search on i over the shorter list:
- If
a_left > b_right, we took too many froma, so movehi = i - 1. - Otherwise
b_left > a_right, we took too few, so movelo = i + 1.
Bounds: i <= m, i <= rank (since j >= 0), and j <= n gives i >= rank - n. So lo = max(0, rank - n) and hi = min(rank, m).
Why it is correct
- A valid cut puts the
ranksmallest elements on the left, so their maximum is therankth smallest value. Ties among equal values do not change that value, so duplicates are handled. - A valid cut always exists when
1 <= k <= m + n: take the firstrankelements of a stable merge. - As
igrows,a_leftdoes not decrease andb_rightdoes not increase, so the search direction is monotonic and binary search converges on a valid cut.
Complexity
- Time:
O(log(min(m, n))). - Space:
O(1).
Reference solution
from typing import List
def kth_largest_two_sorted(first: List[int], second: List[int], k: int) -> int:
a, b = first, second
# k-th largest equals the rank-th smallest.
rank = len(a) + len(b) - k + 1
# Search over the shorter list.
if len(a) > len(b):
a, b = b, a
m, n = len(a), len(b)
lo = max(0, rank - n)
hi = min(rank, m)
while lo <= hi:
i = (lo + hi) // 2
j = rank - i
a_left = float('-inf') if i == 0 else a[i - 1]
a_right = float('inf') if i == m else a[i]
b_left = float('-inf') if j == 0 else b[j - 1]
b_right = float('inf') if j == n else b[j]
if a_left <= b_right and b_left <= a_right:
return int(max(a_left, b_left))
if a_left > b_right:
hi = i - 1
else:
lo = i + 1
raise ValueError('k must be between 1 and the total number of elements')