Binary Search Partition search
260. K-th Element of Two Sorted Arrays
You are given two arrays of integers, first and second, each sorted from smallest to largest, and an integer
k. Put all the values of both arrays into one sorted list, and return the value at position k of that list,
counting from 1. So k = 1 asks for the smallest value of all.
Equal values count separately. If 5 appears twice in first and once in second, it fills three positions in
the list.
Either array can be empty, and k is never more than the total number of values.
Aim for O(log(m + n)) time, where m and n are the lengths of first and second.
Example 1
Input: first = [2, 5, 9, 14]
second = [1, 6, 7, 11, 20]
k = 6
9Explanation: Together the arrays hold 1, 2, 5, 6, 7, 9, 11, 14 and 20. The 6th of these is 9.
Example 2
Input: first = [-6, -3, -3], second = [-8, -3, 0, 4], k = 4
-3Explanation: Together the arrays hold −8, −6, −3, −3, −3, 0 and 4. The three −3s fill positions 3, 4 and 5, so the 4th value is −3.
Example 3
Input: first = [12, 15], second = [], k = 2
15Explanation: second is empty, so the answer is the 2nd value of first, the largest of all.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ first.length ≤ 1050 ≤ second.length ≤ 1051 ≤ k ≤ first.length + second.length-109 ≤ first[i], second[j] ≤ 109firstandsecondare each sorted in non-decreasing order.
Clarifying questions
What you would ask an interviewer before writing any code.