Open In App

How to Find Frequency of an Element in a Deque in C++?

Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors but are more efficient in the case of insertion and deletion of elements at the front and end. In this article, we will learn how to find the frequency of a specific element in a deque in C++.

Example

Input:
Deque<int>dq={1,2,3,5,3,4}

Output:
The frequency of 3 is 2.

Find Frequency of an Element in a Deque in C++

To find the frequency of a specific element in a std::deque in C++, we can use the std::count() function that finds the number of occurrences of the given element in the given range.

Syntax of std::count()

count(dq.begin(), dq.end(), element);

where,

This function will return the frequency of the given element in the form of integer value.

C++ Program to Find Frequency of an Element in a Deque

The following program illustrates how we can find the frequency of a specific element in a deque in C++:

// C++ Program to illustrate how we can find the frequency
// of a specific element in a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    deque<int> dq = { 1, 2, 3, 5, 3, 4 };

    // Print the deque elements
    cout << "Deque Elements: ";
    for (int x : dq) {
        cout << x << " ";
    }
    cout << endl;

    // Declare the element whose frequency is required
    int element = 3;

    // Find the frequency of the specific element
    int frequency = count(dq.begin(), dq.end(), element);

    // Print the frequency
    cout << "Frequency of " << element
         << " is: " << frequency;

    return 0;
}

Output
Deque Elements: 1 2 3 5 3 4 
Frequency of 3 is: 2

Time Complexity: O(N) where N is the size of the deque.
Auxiliary Space: O(1)



Article Tags :