How to Find Mode of All Elements in a Deque in C++?
In C++, deque is a container provided by the STL library of C++ that allows insertion and deletion from both ends. The mode of a deque represents the element that appears most frequently in the container. In this article, we will learn how to find the mode of all elements in a deque in C++.
Example:
Input:
Deque = {1, 2, 3, 4, 5, 2, 2, 3, 4, 4, 4}
Output:
Mode of the deque is: 4
Finding the Mode of All Elements in a Deque in C++
To find the mode of all elements in a std::deque in C++, we can use a std::unordered_map to store the frequencies of each element, then iterate through the map to find the element with the highest frequency which will be the mode of all deque elements.
C++ Program to Find the Mode of All Elements in a Deque
The below example demonstrates how we can find the mode of all elements in a std::deque in C++.
// C++ Program to Find the Mode of All Elements in a Deque
#include <iostream>
#include <deque>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main() {
// Initializing a deque
deque<int> dq = {1, 2, 3, 4, 5, 2, 2, 3, 4, 4, 4};
// Creating a map to store the count of each element
unordered_map<int, int> mp;
// Count the frequency of each element in the deque
for (int num : dq) {
mp[num]++;
}
// Initialize mode with the first element
int mode = dq.front();
// Initialize maxFrequency with 0
int maxFrequency = 0;
// Find the element with greates frequency to get the mode of all elements in the deque
for (auto pair : mp) {
if (pair.second > maxFrequency) {
maxFrequency = pair.second;
mode = pair.first;
}
}
// Print the mode of the all deque elements
cout << "Mode of All Elements in Deque is: " << mode << endl;
return 0;
}
Output
Mode of All Elements in Deque is: 4
Time Complexity: O(N), where N is the size of the deque.
Auxiliary Space: O(N)
Contact Us