![]() |
VOOZH | about |
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
Table of Content
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).
Smallest missing element is 8
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.
Smallest missing element is 8