|
| 1 | +/* |
| 2 | + * Given a sorted array of distinct non-negative integers, find smallest missing element in it. |
| 3 | + * For example, |
| 4 | +
|
| 5 | + * Input: A[] = [0, 1, 2, 6, 9, 11, 15] |
| 6 | + * Output: The smallest missing element is 3 |
| 7 | + |
| 8 | + * Input: A[] = [1, 2, 3, 4, 6, 9, 11, 15] |
| 9 | + * Output: The smallest missing element is 0 |
| 10 | + |
| 11 | + * Input: A[] = [0, 1, 2, 3, 4, 5, 6] |
| 12 | + * Output: The smallest missing element is 7 |
| 13 | + */ |
| 14 | + |
| 15 | +#include <iostream> |
| 16 | +#include <vector> |
| 17 | + |
| 18 | +int missingElement(const std::vector<int>& arr, int low, int high) |
| 19 | +{ |
| 20 | + if (low > high) |
| 21 | + { |
| 22 | + return low; |
| 23 | + } |
| 24 | + |
| 25 | + int mid = low + (high - low)/2; |
| 26 | + |
| 27 | + // if mid index matches the with the mid element, then smallest |
| 28 | + // missing element lies on the right of the mid. |
| 29 | + if (arr[mid] == mid) |
| 30 | + { |
| 31 | + return missingElement(arr, mid + 1, high); |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + return missingElement(arr, low, mid - 1); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +void print(const std::vector<int>& arr) |
| 41 | +{ |
| 42 | + std::cout << "Contents of array:" << std::endl; |
| 43 | + for (auto i : arr) |
| 44 | + { |
| 45 | + std::cout << i << " "; |
| 46 | + } |
| 47 | + std::cout << std::endl; |
| 48 | +} |
| 49 | + |
| 50 | +int main() |
| 51 | +{ |
| 52 | + std::vector<int> arr{0, 1, 2, 3, 4, 6, 7}; |
| 53 | + print(arr); |
| 54 | + int low = 0; |
| 55 | + int high = arr.size() -1; |
| 56 | + std::cout << "Smallest missing element in array is :" << missingElement(arr, low, high) |
| 57 | + << std::endl; |
| 58 | + return 0; |
| 59 | +} |
0 commit comments