Missing Element in Sorted Array - 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 k-th missing number starting from the leftmost number of the array.

The missing numbers are the numbers that are not present in the array but would appear in the complete sequence starting from nums[0].

Example: If nums = [4, 7, 9, 10] and k = 1, the complete sequence starting from 4 would be [4, 5, 6, 7, 8, 9, 10, 11, ...]. The missing numbers are [5, 6, 8, 11, ...], so the 1st missing number is 5.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,7,9,10], k = 1
Output: 5
💡 Note: The complete sequence starting from 4 is [4,5,6,7,8,9,10,11,...]. Missing numbers are [5,6,8,11,...], so the 1st missing is 5.
Example 2 — Larger K
$ Input: nums = [4,7,9,10], k = 3
Output: 8
💡 Note: Missing numbers are [5,6,8,11,...]. The 3rd missing number is 8.
Example 3 — Missing Before Array
$ Input: nums = [1,2,4], k = 3
Output: 6
💡 Note: Complete sequence: [1,2,3,4,5,6,...]. Missing: [3,5,6,...]. The 3rd missing is 6.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ 109
  • nums is sorted in ascending order

Visualization

Tap to expand
Missing Element in Sorted Array INPUT nums = [4, 7, 9, 10] 4 7 9 10 idx 0 idx 1 idx 2 idx 3 Complete Sequence: 4 5 6 7 8 9 10 Present Missing k = 1 Find 1st missing number nums = [4, 7, 9, 10] k = 1 ALGORITHM STEPS 1 Count Missing Before idx missing = nums[i] - nums[0] - i 2 Binary Search Find index where missing >= k 3 Calculate Result result = nums[0] + k + left - 1 4 Return Answer k-th missing number found Missing Count at Each Index idx 0: 4 - 4 - 0 = 0 idx 1: 7 - 4 - 1 = 2 idx 2: 9 - 4 - 2 = 3 idx 3: 10 - 4 - 3 = 3 k=1 is here FINAL RESULT Missing numbers from array: 5 1st 6 2nd 8 3rd k = 1, Answer = 5 The 1st missing number is 5 (between 4 and 7) Output: 5 OK - Verified! Key Insight: For index i, the count of missing numbers before nums[i] is: nums[i] - nums[0] - i Use binary search to find where k-th missing element falls. This gives O(log n) time complexity instead of O(n) for linear search. The answer is nums[0] + k + (position adjustment). TutorialsPoint - Missing Element in Sorted Array | Optimal Solution (Binary Search)
Asked in
Amazon 35 Google 28 Facebook 22 Microsoft 18
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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