Hello there, today we are going to solve Lower Bound STL Hacker Rank Solution in C++.
Table Of Contents 👊Objective
You are given N integers in sorted order. Also, you are given Q queries. In each query, you will be given an integer and you have to tell whether that integer is present in the array. If so, you have to tell at which index it is present and if it is not present, you have to tell the index at which the smallest integer that is just greater than the given number is present.
Lower Bound STL is a function that can be used with a sorted vector. Learn how to use lower bound to solve this problem by clicking here.
Input Format
The first line of the input contains the number of integers N. The next line contains N integers in sorted order. The next line contains Q, the number of queries. Then Q lines follow each containing a single integer Y.
Note: If the same number is present multiple times, you have to print the first index at which it occurs. Also, the input is such that you always have an answer for each query.
Constraints
- 1 <= N <= 10^5
- 1 <= Xi <= 109 ,where Xi is ith element in the array.
- 1 <= Q <= 10^5
- 1 <= Y <= 10^9
Output Format
For each query you have to print "Yes" (without the quotes) if the number is present and at which index(1-based) it is present separated by a space.
If the number is not present you have to print "No" (without the quotes) followed by the index of the next smallest number just greater than that number.
You have to output each query in a new line.
Sample Input
8
1 1 2 2 6 9 9 15
4
1
4
9
15
Sample Output
Yes 1
No 5
Yes 6
Yes 8
Solution - Lower Bound STL in C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n,q,x;
cin >> n;
vector<int> v,a ;
for(int i=0 ; i<n ; i++)
{
cin >> x;
v.push_back(x);
}
cin >> q;
for(int i=0 ; i<q ;i++)
{
cin >> x;
auto low = lower_bound(v.begin(),v.end(),x);
if(v[low-v.begin()]==x){
cout << "Yes " << low-v.begin()+1 << '\n';
}
else cout << "No " << low-v.begin()+1 << '\n';
}
return 0;
}
Disclaimer: The above Problem (Lower Bound STL) is generated by Hacker Rank but the Solution is Provided by Sloth Coders. This tutorial is only for Educational and Learning Purpose.