Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
```
Solution:
In c++

#include<vector>
using namespace std;
int firstOcc(vector<int>& arr, int n, int key) { // finding the first occurrence of that element

int s = 0, e = n-1;
int mid = s + (e-s)/2;
int ans = -1;
while(s<=e) {

if(arr[mid] == key){
ans = mid;
e = mid - 1;
}
else if(key > arr[mid]) { //Shifting to right
s = mid + 1;
}
else if(key < arr[mid]) { //Shifting to left
e = mid - 1;
}

mid = s + (e-s)/2;
}
return ans;
}

int lastOcc(vector<int>& arr, int n, int key) { //finding the last occurrence of that element

int s = 0, e = n-1;
int mid = s + (e-s)/2;
int ans = -1;
while(s<=e) {

if(arr[mid] == key){
ans = mid;
s = mid + 1;
}
else if(key > arr[mid]) { // Shifting to right
s = mid + 1;
}
else if(key < arr[mid]) { //Shifting to left
e = 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;
}
```