Skip to content

Commit 02404d8

Browse files
committed
Smallest missing number
1 parent a25ec10 commit 02404d8

File tree

2 files changed

+62
-2
lines changed

2 files changed

+62
-2
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
| Current Status| Stats |
88
| :------------: | :----------: |
9-
| Total Problems | 146 |
10-
| Current Streak | 10 days |
9+
| Total Problems | 147 |
10+
| Current Streak | 11 days |
1111
| Longest Streak | 91 ( August 17, 2015 - November 15, 2015 ) |
1212

1313
</center>
@@ -180,6 +180,7 @@ Include contains single header implementation of data structures and some algori
180180
| Find the common elements in 3 sorted vectors | [commonIn3Arrays.cpp](sort_search_problems/commonIn3Arrays.cpp) |
181181
| Find all the pairs with a given sum in an unsorted array/vector | [find_pairs_with_sum.cpp](sort_search_problems/find_pairs_with_sum.cpp) |
182182
| Given an array, find peak element in it. A peak element is an element that is greater than its neighbors.| [peak_element.cpp](sort_search_problems/peak_element.cpp) |
183+
| Given a sorted array of distinct non-negative integers, find smallest missing element in it.| [smallest_missing.cpp](sort_search_problems/smallest_missing.cpp)|
183184

184185
### Graph Problems
185186
| Problem | Solution |
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)