1539.Kth Missing Positive Number
Problem description:
Given an array arr
of positive integers sorted in a strictly increasing order, and an integer k
.
Find the kth
positive integer that is missing from this array.
Example 1:
1 | Input: arr = [2,3,4,7,11], k = 5 |
Example 2:
1 | Input: arr = [1,2,3,4], k = 2 |
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j]
for1 <= i < j <= arr.length
Solution:
Relation between nums[idx]
and idx
could help to find missing number
We need a way to check on how many positive integers are missing before the given array element to use binary search. To do that, let’s compare the input array [2, 3, 4, 7, 11]
with an array with no missing integers: [1, 2, 3, 4, 5]
. The number of missing integers is a simple difference between the corresponding elements of these two arrays:
- Before
2
, there is2 - 1 = 1
missing integer. - Before
3
, there is3 - 2 = 1
missing integer. - Before
4
, there is4 - 3 = 1
missing integer. - Before
7
, there are7 - 4 = 3
missing integers. - Before
11
, there are11 - 5 = 6
missing integers.
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: