Talentd
FleetCode

1060. Missing Element in Sorted Array

Medium59.7% acceptance4 companiesPremium elsewhere, free here

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.

Example 1:

Input: nums = [4,7,9,10], k = 1
Output: 5
Explanation: The first missing number is 5.

Example 2:

Input: nums = [4,7,9,10], k = 3
Output: 8
Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.

Example 3:

Input: nums = [1,2,4], k = 3
Output: 6
Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 1 <= nums[i] <= 107
  • nums is sorted in ascending order, and all the elements are unique.
  • 1 <= k <= 108
Follow up: Can you find a logarithmic time complexity (i.e., O(log(n))) solution?

Asked at 4 companies

Hints open one at a time

Hint 1
First define a function f(x) that counts the number of missing elements until x.
Hint 2
Then use binary search with the given function f(x) to find the kth missing element.
11:18
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[4,7,9,10]
1
Input
[4,7,9,10]
3
Input
[1,2,4]
3
Your code is saved on this device.Solution