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
Hotel Floor Plan - Finding Missing RoomsExisting Rooms: [4, 7, 9, 10] | Looking for 3rd missing room4Exists5Missing #16Missing #27Exists8Missing #3!9Exists10ExistsBinary Search finds room 8 efficiently without checking every number!
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.
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 15
63.2K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen