Missing Element in Sorted Array - Problem
Imagine you have a sorted array of unique integers, but it's not a perfect sequence - there are gaps! Your mission is to find the k-th missing number in the sequence, counting from the leftmost element.
For example, if you have the array [4, 7, 9, 10] and k = 1, the missing numbers starting from 4 are: 5, 6, 8, 11, 12... So the 1st missing number is 5.
This problem tests your ability to work with sorted arrays and efficiently calculate missing elements without generating all possibilities.
Goal: Return the k-th missing number in the sequence defined by the sorted array.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [4, 7, 9, 10], k = 1
โบ
Output:
5
๐ก Note:
The missing numbers starting from 4 are [5, 6, 8, 11, 12, ...]. The 1st missing number is 5.
example_2.py โ Multiple Missing
$
Input:
nums = [4, 7, 9, 10], k = 3
โบ
Output:
8
๐ก Note:
The missing numbers are [5, 6, 8, 11, 12, ...]. The 3rd missing number is 8.
example_3.py โ Beyond Array Range
$
Input:
nums = [1, 2, 4], k = 3
โบ
Output:
6
๐ก Note:
Missing numbers are [3, 5, 6, 7, ...]. The 3rd missing number is 6, which is beyond the array's range.
Constraints
- 1 โค nums.length โค 5 ร 104
- 1 โค nums[i] โค 109
- nums is sorted in ascending order
- 1 โค k โค 108
- All values in nums are unique
Visualization
Tap to expand
Understanding the Visualization
1
Identify Existing Rooms
We have rooms [4, 7, 9, 10] on our floor
2
Calculate Missing Rooms
Between rooms 4 and 7, rooms 5 and 6 are missing
3
Use Binary Search
Instead of checking each room number, jump to sections with missing rooms
4
Find Target Room
Locate exactly where the k-th missing room would be
Key Takeaway
๐ฏ Key Insight: Use the formula `nums[i] - nums[0] - i` to calculate missing elements up to any position, enabling efficient binary search instead of linear counting.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code