# Count number of occurrences (or frequency) in a sorted array

In this tutorial, we will learn how to find the number of occurrences for any given element in a sorted array using C++ program? By Radib Kar Last updated : August 10, 2023

## Problem statement

If the array is **[2,3,3,4,5,6,6,6,6,7]** and if the element is **6** then it has frequency **4**.

We can solve this by either using the linear search or binary search.

## Count number of occurrences in a sorted array using linear search

Keep searching elements by elements until you find the given element. Once you find the given element keep incrementing the frequency count until you meet any other value. Since the array is sorted it's guaranteed there won't be any other occurrence of this element after that. Below is the code snippet for reference. This has a time complexity of * O(n)*.

void findFrequencyeNaive(vector& arr, int num) { cout << "..............Using naive search......\n"; //O(n) time complexity int freq = 0; for (int i = 0; i < arr.size(); i++) { if (arr[i] > num) break; if (arr[i] == num) freq++; } if (freq == 0) cout << "No such occurences found"; else cout << "Frequency of given element " << d << " is: " << freq << "\n"; return; }

## Count number of occurrences in a sorted array using binary search

We can also use a binary search. Using binary search we need o find two things, one is the first occurrence of the element and another is the last occurrence of the element.

Below is the code snippe for finding fast & last occurrence using binary search. The frequency count would be *last occurrence index - first occurrence index +1*.

//code snippet to find first occurence int first_occurence(vector& arr, int d) { int start = 0, end = arr.size() - 1; int index = -1; while (start <= end) { int mid = start + (end - start) / 2; if (arr[mid] == d) { index = mid; end = mid - 1; } else if (arr[mid] > d) { end = mid - 1; } else { start = mid + 1; } } return index; } //code snippet to find the last occurrence int last_occurence(vector & arr, int d) { int start = 0, end = arr.size() - 1; int index = -1; while (start <= end) { int mid = start + (end - start) / 2; if (arr[mid] == d) { index = mid; start = mid + 1; } else if (arr[mid] > d) { end = mid - 1; } else { start = mid + 1; } } return index; }

## C++ program to count number of occurrences (or frequency) in a sorted array

#include <bits/stdc++.h> using namespace std; //naive approach void findFrequencyeNaive(vector<int>& arr, int num) { int d; cout << "..............Using naive search......\n"; //O(n) time complexity int freq = 0; for (int i = 0; i < arr.size(); i++) { if (arr[i] > num) break; if (arr[i] == num) freq++; } if (freq == 0) cout << "No such occurences found"; else cout << "Frequency of given element " << d << " is: " << freq << "\n"; return; } //function to find first occurence int first_occurence(vector<int>& arr, int d) { int start = 0, end = arr.size() - 1; int index = -1; while (start <= end) { int mid = start + (end - start) / 2; if (arr[mid] == d) { index = mid; end = mid - 1; } else if (arr[mid] > d) { end = mid - 1; } else { start = mid + 1; } } return index; } //function to find last occurence int last_occurence(vector<int>& arr, int d) { int start = 0, end = arr.size() - 1; int index = -1; while (start <= end) { int mid = start + (end - start) / 2; if (arr[mid] == d) { index = mid; start = mid + 1; } else if (arr[mid] > d) { end = mid - 1; } else { start = mid + 1; } } return index; } void findFrequencyEfficient(vector<int>& arr, int d) { cout << "..............Using efficient approach(binary search)......\n"; //O(logn) time complexity //find out tyhe first occurence int first_index = first_occurence(arr, d); if (first_index == -1) { cout << "No such occurences found"; return; } int last_index = last_occurence(arr, d); int freq = last_index - first_index + 1; cout << "Frequency of given element " << d << " is: " << freq << "\n"; } int main() { cout << "Enter number of elements\n"; int n; cin >> n; vector<int> arr(n); cout << "Enter the elements\n"; for (int i = 0; i < n; i++) cin >> arr[i]; cout << "Enter the element\n"; int d; cin >> d; //using navive approach findFrequencyeNaive(arr, d); //using binary search findFrequencyEfficient(arr, d); return 0; }

## Output

Enter number of elements 10 Enter the elements 2 3 3 4 4 6 6 6 6 7 Enter the element 6 ..............Using naive search...... Frequency of given element 6 is: 4 ..............Using efficient approach(binary search)...... Frequency of given element 6 is : 4

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Dynamic Programming (Components, Applications and Elements)
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!