Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The k-th smallest of two sorted arrays

Hard · Target 25 minutes · Binary search · Type asked atGoogleCitadelTwo Sigma

Given two arrays a and b, each sorted in non-decreasing order (either may be empty, but not both), and an integer k with 1 ≤ k ≤ |a| + |b|, return the k-th smallest value of the two arrays taken together. Use O(log k) steps, without merging.

Examples

InputOutputWhy
a = [2, 3, 6, 7, 9], b = [1, 4, 8, 10], k = 56Merged: 1, 2, 3, 4, 6, 7, 8, 9, 10.
a = [1, 3], b = [2], k = 22
a = [], b = [5, 9], k = 15

Constraints

  • 0 ≤ |a|, |b| ≤ 10⁵, |a| + |b| ≥ 1
  • 1 ≤ k ≤ |a| + |b|
  • −10⁹ ≤ values ≤ 10⁹

Hints

Hint 1

Merging until the k-th element costs O(k). The goal is to throw away many candidates at a time.

Hint 2

Take h = k / 2 elements from the front of each array and compare the last of each: a[h − 1] and b[h − 1].

Hint 3

If a[h − 1] ≤ b[h − 1], at most 2h − 2 elements can come before a[h − 1], so it ranks below k, and so does everything before it in a. Drop those h elements and look for the (k − h)-th of what is left.

Where people lose marks

  • Taking h elements from an array that has fewer left: clamp the block to what remains.
  • Discarding the block of the larger element: it may hold the answer.
  • Forgetting k = 1, where h = 0 and nothing would be discarded: the loop never ends.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.