Skip to content

Commit 2a1ff96

Browse files
Create Namanjain6152.md
1 parent 594d705 commit 2a1ff96

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

findPos/Namanjain6152.md

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<!-- finding first position of given target using binary search -->
2+
3+
int firstOccur(vector<int>& arr, int n, int k){
4+
int i=0,j=n-1;
5+
int finalocc=-1;
6+
while(i<=j){
7+
int mid= i+(j-i)/2;
8+
if(arr[mid]==k){
9+
finalocc=mid;
10+
j=mid-1;
11+
}
12+
else if(arr[mid]>k){
13+
j=mid-1;
14+
}
15+
else{
16+
i= mid+1;
17+
}
18+
}
19+
return finalocc;
20+
}
21+
22+
<!-- finding last position of target using binary search -->
23+
int lastOccur(vector<int>& arr, int n, int k){
24+
int i=0,j=n-1;
25+
int finalocc=-1;
26+
while(i<=j){
27+
int mid= i+(j-i)/2;
28+
if(arr[mid]==k){
29+
finalocc=mid;
30+
i=mid+1;
31+
}
32+
else if(arr[mid]>k){
33+
j=mid-1;
34+
}
35+
else{
36+
i= mid+1;
37+
}
38+
}
39+
return finalocc;
40+
}
41+
42+
<!-- function that returns the pair of first and last position of given target -->
43+
pair<int, int> firstAndLastPosition(vector<int>& arr, int n, int k)
44+
{
45+
// Write your code here
46+
int ans1= firstOccur(arr,n,k);
47+
int ans2= lastOccur(arr,n,k);
48+
return {ans1,ans2};
49+
50+
}

0 commit comments

Comments
 (0)