Search⌘ K
AI Features

Solution: Count Element Occurrence

Explore three methods to count the occurrences of an element in an array, including brute force and binary search techniques. Understand their respective time complexities and how to apply them to optimize solutions for searching and counting in sorted arrays.

Solution #1: Brute Force with Linear Search

C++
#include <iostream>
using namespace std;
int calcFreq(int arr[], int arrSize, int s) {
int count = 0;
for(int i = 0; i < arrSize; i++) {
if(arr[i] == s)
count++;
}
return count;
}
int main() {
int arr[] = {-5,-3,0,1,3,3,3,3,4,5};
cout << calcFreq(arr, 10, 3) << endl;
}

This is an extremely simple way to solve this problem. We simply initialize a variable to keep count called, count to 0 and then iterate over the array, increasing count by 1 every time the target value is encountered.

Time Complexity

The time complexity of this algorithm is in ...