VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-first-missing-number/

⇱ Smallest Missing Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest Missing Number

Last Updated : 27 Jan, 2026

Given a sorted array arr[], of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array.

Examples:

Input: arr[] = [0, 1, 2, 6, 9], m = 10
Output: 3
Explanation: Missing numbers are 3, 4, 5, 7 and 8. But the smallest missing number is 3.

Input: arr[] = [4, 5, 10, 11], m = 12 
Output: 0

Input: arr[] = [0, 1, 2, 3], m = 5 
Output: 4

[Naive Approach] Using Linear Search - O(n) Time and O(1) Space

In a sorted array of distinct non-negative integers, if no number is missing, each element should satisfy arr[i] = i. The array is scanned linearly to find the first index i where arr[i] != i. This index represents the smallest missing number. If no such index exists, it means all numbers from 0 to n-1 are present, so the smallest missing number is n (i.e., arr[n-1] + 1).


Output
Smallest missing element is 8

[Expected Approach] Using Binary Search - O(log(n)) Time and O(1) Space

Since the array is sorted and contains distinct non-negative integers, this property allows us to apply binary search.

If at any index mid:

  • arr[mid] == mid, then all numbers from 0 to mid are present, so the smallest missing number must lie in the right half.
  • arr[mid] > mid, then a number is missing in the left half, including possibly mid itself.

By repeatedly narrowing the search space using this condition, binary search converges to the first index where arr[i] ≠ i.

After the search ends, the pointer low indicates the smallest missing number.


Output
Smallest missing element is 8
Comment
Article Tags: