-
Notifications
You must be signed in to change notification settings - Fork 0
/
First and last Occurence in binary Search.txt
112 lines (97 loc) · 2.75 KB
/
First and last Occurence in binary Search.txt
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
You have been given a sorted array/list ARR consisting of ‘N’ elements. You are also given an integer ‘K’.
Now, your task is to find the first and last occurrence of ‘K’ in ARR.
Note :
1. If ‘K’ is not present in the array, then the first and the last occurrence will be -1.
2. ARR may contain duplicate elements.
For example, if ARR = [0, 1, 1, 5] and K = 1, then the first and last occurrence of 1 will be 1(0 - indexed) and 2.
Input Format
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains two single-space separated integers ‘N’ and ‘K’, respectively.
The second line of each test case contains ‘N’ single space-separated integers denoting the elements of the array/list ARR.
Output Format :
Return two single-space separated integers denoting the first and the last occurrence of ‘K’ in ARR, respectively.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 5000
0 <= K <= 10^5
0 <= ARR[i] <=10^5
Time Limit : 1 second
Sample Input 1:
2
6 3
0 5 5 6 6 6
8 2
0 0 1 1 2 2 2 2
Sample Output 1:
-1 -1
4 7
Explanation Of Sample Output 1:
For the first test case, 3 is not present in the array. Hence the first and last occurrence of 3 is -1 and -1.
For the second test case, the first occurrence of 2 in at index 4 and last occurrence is at index 7.
Sample Input 2:
2
4 0
0 0 0 0
1 2
2
Sample Output 2:
0 3
0 0
Solution
int firstOcc(vector<int> &arr , int n , int key)
{
int s = 0 , e = n-1;
int mid = s + (e-s)/2;
int ans = -1;
while( s <= e)
{
if( key == arr[mid])
{
ans = mid;
e = mid - 1;
}
else if(key < arr[mid])
{
e = mid -1;
}
else
{
s = mid + 1;
}
mid = s + (e-s)/2;
}
return ans ;
}
int lastOcc(vector<int> &arr , int n , int key)
{
int s = 0 , e = n-1;
int mid = s + (e-s)/2;
int ans = -1;
while( s <= e)
{
if( key == arr[mid])
{
ans = mid;
s = mid + 1;
}
else if(key < arr[mid])
{
e = mid -1;
}
else
{
s = mid + 1;
}
mid = s + (e-s)/2;
}
return ans ;
}
pair<int, int> firstAndLastPosition(vector<int>& arr, int n, int k)
{
pair <int , int> p;
p.first = firstOcc(arr, n ,k);
p.second = lastOcc(arr,n , k);
return p;
}