Missing Element in Sorted Array — LeetCode 1060 Python Solution
- Problem
- #1060
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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
- Input
- nums = [4,7,9,10], k = 1
- Output
- 5
- Explanation
- The first missing number is 5.
Python solution
class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
def missing(i: int) -> int:
return nums[i] - nums[0] - i
n = len(nums)
if k > missing(n - 1):
return nums[n - 1] + k - missing(n - 1)
l, r = 0, n - 1
while l < r:
mid = (l + r) >> 1
if missing(mid) >= k:
r = mid
else:
l = mid + 1
return nums[l - 1] + k - missing(l - 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1060. Missing Element in Sorted Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1060. Missing Element in Sorted Array?
- LeetCode 1060. Missing Element in Sorted Array is rated Medium on LeetCode.
- What topics does LeetCode 1060. Missing Element in Sorted Array cover?
- LeetCode 1060. Missing Element in Sorted Array is tagged Array and Binary Search on LeetCode.
- Is LeetCode 1060. Missing Element in Sorted Array a premium problem?
- Yes. LeetCode 1060. Missing Element in Sorted Array is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.