Solution: Count Element Occurrence
Here is a detailed analysis of the different ways to count the frequency of a number in a sorted array of integers.
Solution #1: Brute force with linear search
This is an extremely simple way to solve this problem. We simply initialize a variable, count, to keep count and set it to 0 (line 3). We then iterate over the array (line 5), increasing count by one every time the key (value to search) is encountered (lines 7-9).
Time complexity
The time complexity of this algorithm is in since the array is iterated over once.
Solution #2: Using binary search
This is also a very simple solution. It draws upon the fact that if an element exists in a sorted array, all of its ...