KatInterview

Kth Biggest Value Across a Pair of Ascending Lists

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchsorted-arraysorder-statistics

Last 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 both 5.
  • Either list may be empty, but together they hold at least k elements.
  • 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

  • first and second are sorted in non-decreasing order.
  • 0 <= len(first), len(second) and len(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.