3. What will be the output of the following code snippet?
int arr[] = {1, 2, 2, 2, 3, 4, 5};
int n = 7;
int x = 2;
int countOccurrences(int arr[], int n, int x) {
int first = -1, last = -1;
int low = 0, high = n - 1;
// Find first occurrence
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
first = mid;
high = mid - 1;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (first == -1) return 0;
low = first; high = n - 1;
// Find last occurrence
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
last = mid;
low = mid + 1;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return last - first + 1;
}
std::cout << countOccurrences(arr, n, x) << std::endl;