-
Notifications
You must be signed in to change notification settings - Fork 0
/
First_and_last_occurrences_using_upper_and_lower_bound.cpp
76 lines (69 loc) · 1.48 KB
/
First_and_last_occurrences_using_upper_and_lower_bound.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
int lower_bound(int arr[], int n, int x)
{
int ans = -1;
int low = 0;
int high = n-1;
while(low <= high)
{
int mid = (low + high)/2;
if(arr[mid] >= x)
{
ans = mid;
high = mid-1;
}
else low = mid+1;
}
return ans;
}
int upper_bound(int arr[], int n, int x)
{
int low = 0;
int high = n-1;
while(low <= high)
{
int mid = (low + high)/2;
if(arr[mid] <= x)
{
low = mid+1;
}
else high = mid-1;
}
return low;
}
vector<int> find(int arr[], int n , int x )
{
int i = lower_bound(arr, n, x);
if (i == -1 || (i < n && arr[i] != x)) {
return {-1, -1};
}
int j = upper_bound(arr, n, x)-1;
return {i, j};
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n,x;
cin>>n>>x;
int arr[n],i;
for(i=0;i<n;i++)
cin>>arr[i];
vector<int> ans;
Solution ob;
ans=ob.find(arr,n,x);
cout<<ans[0]<<" "<<ans[1]<<endl;
}
return 0;
}
// } Driver Code Ends