-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirst and last occurrences of x.cpp
121 lines (107 loc) · 2.14 KB
/
First and last occurrences of x.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/*
First and last occurrences of x
Input:
1
9 5
1 3 5 5 5 5 67 123 125
Output:
2 5
TC: O(logn) and SC: O(1)
Code uses Binary Search to find the first and last occurrence of a number in a sorted array.
Another Approach:
vector<int> find(int arr[], int n, int x)
{
int low = 0, high = n - 1;
while (low <= high)
{
if (arr[low] != x)
{
low++;
}
if (arr[high] != x)
{
high--;
}
if (arr[low] == x && arr[high] == x)
{
return {low, high};
}
}
if (low > high)
{
return {-1, -1};
}
}
*/
class Solution
{
public:
vector<int> find(int arr[], int n, int x)
{
vector<int> ans(2, -1);
// Find the first occurrence of x
int left = 0, right = n - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == x)
{
ans[0] = mid;
right = mid - 1;
}
else if (arr[mid] < x)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
// Find the last occurrence of x
left = 0;
right = n - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == x)
{
ans[1] = mid;
left = mid + 1;
}
else if (arr[mid] < x)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return ans;
}
};
//{ 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