Skip to content

Commit b70127c

Browse files
committed
Day 32 - specialized binary search
1 parent 4cb5b6f commit b70127c

File tree

6 files changed

+50
-0
lines changed

6 files changed

+50
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,8 @@ Include contains single header implementation of data structures and some algori
9494
| :------------ | :----------: |
9595
| We have series of n daily price quotes for a stock. We need to calculate span of stock's price for all n days. Span for ith day is defined as maximum number of consecutive days, for which the price of the stock was less than or equal to ith day. For stock quotes {100, 60, 70, 65, 80, 85} span will be {1, 1, 2, 1, 4, 5}. Span for day 1 is always 1, now for day 2 stock is at 60, and there is no day befor it when stock was less than 60. So span remains 1. For day 3, the stock is priced at 70, so its span is 2, as previous day it was 60, and so on. | [stock_span_problem.cpp](stack_problems/stock_span_problem.cpp) |
9696

97+
### Sort and Search Problems
98+
| Problem | Solution |
99+
| :------------ | :----------: |
100+
| Given a sorted vector, return first index of the occurrence of a value in vector, if number does not exist, return -1 | [first_occurrence_binary_search.cpp](sort_search_problems/first_occurrence_binary_search.cpp) |
101+
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Given a sorted array, and a number.
3+
* User binary search to find the number, and return the index.If number occurrs multiple times
4+
* return the first index. If number does not exist, return -1.
5+
*/
6+
7+
#include <iostream>
8+
#include <vector>
9+
10+
int firstOccurrenceBinarySearch( const std::vector<int> & vec, int key )
11+
{
12+
int high = vec.size() - 1;
13+
int low = 0;
14+
int firstOccurrance = -1;
15+
while ( low <= high ) {
16+
int mid = (high + low) / 2;
17+
if ( key < vec[mid] ) {
18+
high = mid - 1;
19+
} else if ( key > vec[mid]) {
20+
low = mid + 1;
21+
} else {
22+
firstOccurrance = mid;
23+
high = mid - 1 ;
24+
}
25+
}
26+
return firstOccurrance;
27+
}
28+
29+
void printVec( const std::vector<int> & vec)
30+
{
31+
for ( auto & i : vec ) {
32+
std::cout << i << " ";
33+
}
34+
std::cout << std::endl;
35+
}
36+
37+
int main()
38+
{
39+
std::vector<int> vec{ 1, 1, 1, 1, 2, 2, 3, 3, 3 };
40+
std::cout << "Contents of vector:\n";
41+
printVec(vec);
42+
std::cout << "First Occurrence of 2 in the vector is at index : "
43+
<< firstOccurrenceBinarySearch(vec, 2) << std::endl;
44+
return 0;
45+
}

0 commit comments

Comments
 (0)