-
Notifications
You must be signed in to change notification settings - Fork 0
/
028. find total number of occurrences in a sorted array.cpp
75 lines (68 loc) · 1.76 KB
/
028. find total number of occurrences in a sorted array.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
Number of occurrence - GeeksForGeeks
Given a sorted array Arr of size N and a number X, you need to find the number of occurrences of X in Arr.
Input:
N = 7, X = 2
Arr[] = {1, 1, 2, 2, 2, 2, 3}
Output: 4
Explanation:
2 occurs 4 times in the given array.
Code:
class Solution {
private:
int firstOccurence(int arr[], int n, int x) {
int start = 0;
int end = n - 1;
int mid = start + (end - start) / 2;
int res = -1;
while(start <= end) {
if(arr[mid] == x) {
res = mid;
end = mid - 1;
}
else if(arr[mid] < x) {
start = mid + 1;
}
else {
end = mid - 1;
}
mid = start + (end - start) / 2;
}
return res;
}
int lastOccurence(int arr[], int n, int x) {
int start = 0;
int end = n - 1;
int mid = start + (end - start) / 2;
int res = -1;
while(start <= end) {
if(arr[mid] == x) {
res = mid;
start = mid + 1;
}
else if(arr[mid] < x) {
start = mid + 1;
}
else {
end = mid - 1;
}
mid = start + (end - start) / 2;
}
return res;
}
public:
/* if x is present in arr[] then returns the count
of occurrences of x, otherwise returns 0. */
int count(int arr[], int n, int x) {
// code here
int first = firstOccurence(arr, n, x);
int last = lastOccurence(arr, n, x);
int ans = 0;
if(first < 0 && last < 0) {
ans = 0;
}
else {
ans = last - first + 1; //counting principle
}
return ans;
}
};