KatInterview

Kth Element in Union of Two Sorted Lists

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraystwo-pointers

Last 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.