Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.
solution
First of all, the number of numbers missing from some array index m is equal to nums[m]-nums[0]-m.
We can bisect_left on k to find the first index where num_missing is greater than or equal to k.
Then the calculation at the end goes as follows:
nums[0]+kis equal to the kth missing element, if there were no other values innumsexcept for the first value.lrepresents how many values in the range from[nums[0], nums[0]+k]already exist in the array. This means that we have to push further ahead to find our kth element.- We subtract 1 because the
bisect_leftendslat the first index that haskmissing elements, meaning that the element atnums[l]does not interfere with our kth missing element, so we ignore it and movelback by 1.
def missingElement(self, nums: List[int], k: int) -> int:
# bisect_left
l, r = 0, len(nums)
while l < r:
m = (l+r)//2
num_missing = nums[m]-nums[0]-m
if num_missing < k:
l = m+1
else:
r = m
# base
# + num_missing
# + offset
return nums[0] + k + l - 1