oneby7

Binary Search Searching the answer

248. Kth Missing Positive Number

Easy

You are given an array arr of positive integers in strictly increasing order, and an integer k. A positive integer is missing if arr does not contain it.

Go through the positive integers 1, 2, 3, … in order and skip every number that is in arr. Return the k-th number that is left, the k-th missing number. It can be larger than every element of arr.

Example 1

Input: arr = [3, 4, 7, 11], k = 5

Output: 8

Explanation: The missing numbers are 1, 2, 5, 6, 8, 9, 10, 12, and so on. The fifth of them is 8.

Example 2

Input: arr = [1, 2, 3, 4], k = 3

Output: 7

Explanation: No number below 4 is missing. The missing numbers start after the array, at 5, 6, 7, so the third is 7.

Example 3

Input: arr = [1000000000], k = 1000000000

Output: 1000000001

Explanation: The numbers from 1 to 999,999,999 are all missing. 109 is in arr, so the next missing number, 109 + 1, is the 109-th.

Check your understanding

Work out the answer for this input before you write any code.

arr = [2, 5, 6], k = 3

Constraints

  • 1 ≤ arr.length ≤ 105
  • 1 ≤ arr[i] ≤ 109
  • arr[i] < arr[i + 1] (strictly increasing)
  • 1 ≤ k ≤ 109

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.