oneby7

Binary Search Partition search

260. K-th Element of Two Sorted Arrays

Hard

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

Output: 9

Explanation: 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

Output: -3

Explanation: 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

Output: 15

Explanation: 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.

first = [1, 4, 7], second = [2, 3, 10], k = 4

Constraints

  • 0 ≤ first.length ≤ 105
  • 0 ≤ second.length ≤ 105
  • 1 ≤ k ≤ first.length + second.length
  • -109 ≤ first[i], second[j] ≤ 109
  • first and second are each sorted in non-decreasing order.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.