-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.2.3.cpp
45 lines (37 loc) · 815 Bytes
/
16.2.3.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
#include <iostream>
using namespace std;
// Print First and Last Occurrence of a number in an array
int firstOccurrence(int arr[], int n, int i, int key){
if(i == n){
return -1;
}
if(arr[i] == key){
return i;
}
return firstOccurrence(arr, n, i+1, key);
}
int lastOccurrence(int arr[], int n, int i, int key){
// Base condition
if(i == n){
return -1;
}
int restArray = lastOccurrence(arr, n, i+1, key);
if(restArray != -1){
return restArray;
}
if(arr[i] == key){
return i;
}
return -1;
}
int main(){
int n, key;
cin>>n>>key;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
cout<<firstOccurrence(arr, n, 0, key)<<" ";
cout<<lastOccurrence(arr, n, 0, key);
return 0;
}