C++ Program to Find the Number of occurrences of a given Number using Binary Search approach



In this article, our task is to find the number of occurrences of a given number using binary search. The binary search algorithm works on the divide-and-conquer principle as it keeps dividing the array in half before searching. To search for an element in an array using binary search, it should be sorted.

In the sorted array, we find the middle element and compare it with the element that has to be searched, and based on the comparison, we either search in the left or right sub-array or return the middle element. Following are some example scenarios:

Scenario 1

Input: arr = {10, 7, 3, 10, 4, 7, 10, 4, 3},  target = 10
Output: 3

Scenario 2

Input: arr = {11, 5, 9, 1, 3, 7, 11, 7, 9},  target = 9
Output: 2

Counting Occurrences of Given Number using Binary Search

The steps to count the number of times a number occurs in an array using the binary search are given below:

  • Sort the given array in ascending order using the sort() function for applying binary search.
  • The findFirst() function finds the first occurrence of the target element using binary search. Even if the target element is found, keep searching the left side of the array.
  • Similarly, the findLast() function finds the last occurrence of the target element using binary search. Even if the target element is found, keep searching the right side of the array.
  • The countOccurrences() function first checks if the first occurrence is valid, then calculates and returns the total occurrence of target element using last - first + 1.
  • If the returned value is greater than 0, we return the count; otherwise, we return element not found.

C++ Program to Count Occurrences of Given Number using Binary Search

Here is a code example of the above mentioned steps for counting the occurrences of a given number using binary search:

#include <iostream>
#include <algorithm>
using namespace std;

// finding the first occurrence of target using Binary Search
int findFirst(int arr[], int n, int target)
{
    int left = 0, right = n - 1;
    int firstPos = -1;

    while (left <= right)
    {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target)
        {
            firstPos = mid;
            right = mid - 1;
        }
        else if (arr[mid] < target)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    return firstPos;
}

// finding the last occurrence of target using Binary Search
int findLast(int arr[], int n, int target)
{
    int left = 0, right = n - 1;
    int lastPos = -1;

    while (left <= right)
    {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target)
        {
            lastPos = mid;
            left = mid + 1;
        }
        else if (arr[mid] < target)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    return lastPos;
}

// Counting the occurrence of target
int countOccurrences(int arr[], int n, int target)
{
    int first = findFirst(arr, n, target);

    if (first == -1)
    {
        return 0;
    }

    int last = findLast(arr, n, target);
    return last - first + 1;
}

void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main()
{
    int arr[] = {10, 7, 3, 10, 4, 7, 10, 4, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 10;

    cout << "Given array: ";
    printArray(arr, n);

    sort(arr, arr + n);

    cout << "Sorted array: ";
    printArray(arr, n);

    cout << "\nTarget element: " << target << endl;

    int count = countOccurrences(arr, n, target);

    if (count > 0)
    {
        cout << "Element " << target << " is occurring " << count << " times." << endl;
    }
    else
    {
        cout << "Element not found" << endl;
    }

    return 0;
}

The output of the above code is as follows:

Given array: 10 7 3 10 4 7 10 4 3 
Sorted array:3 3 4 4 7 7 10 10 10 

Target element: 10
Element 10 is occurring 3 times.

Counting Occurrences of Given Number using C++ STL Functions

The code given below is an alternate way of writing the previous code. In the previous approach, we have implemented binary search twice to find the first and last occurrence of the target element. Here, we are using two STL functions, i.e., lower_bound() and upper_bound(), to get the first and last occurrence of the target element, respectively.

#include <iostream>
#include <algorithm>
using namespace std;

void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
}

int main()
{
    int arr[] = {10, 7, 3, 10, 4, 7, 10, 4, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 7;

    cout << "Given array: ";
    printArray(arr, n);

    sort(arr, arr + n);

    cout << "Sorted array: ";
    printArray(arr, n);
    cout << "\n";

    int first = lower_bound(arr, arr + n, target) - arr;
    int last = upper_bound(arr, arr + n, target) - arr;

    cout << "Target element: " << target << "\n";
    if (first == n || arr[first] != target)
        cout << "Element " << target << " not found in array.";
    else
        cout << "Element " << target << " is occurring " << (last - first) << " times.";

    return 0;
}

The output of the above code is given below:

Given array: 10 7 3 10 4 7 10 4 3 
Sorted array: 3 3 4 4 7 7 10 10 10 

Target element: 7
Element 7 is occurring 2 times.

Complexity Comparison

Here is a comparison of the time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Manual Binary Search O(n log n) due to sorting, otherwise O(log n) O(1)
Using STL Functions O(n log n) due to sorting, otherwise O(log n) O(1)
Updated on: 2025-08-20T13:43:41+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements