How to Find the Mode of All Elements in a List in C++?
Last Updated :
16 Apr, 2024
In C++, a list is a sequence container used to store data of similar type in non-contiguous memory locations. The mode of a list represents the element that occurs most frequently in the container. In this article, we will learn how to find the mode of a list in C++.
Example:
Input:
myList = {1, 2, 3, 4, 5, 2, 2, 3, 4, 4, 4};
Output:
Mode of the list is :4
Finding the Mode of All Elements in a List in C++
To find the mode of all elements in a std::list in C++, we need to count the frequency of all elements in the list. To do that, we can use the std::unordered_map
container where the key will represent the list element and its value will represent its frequency.
Approach
- Create an
unordered_map
of <int, int>
. - Iterate over the list and if the list element is present in the
unordered_map
, increment its value. - If the list element is not present, add the list element as a key with value 1.
- Iterate again on the map and find the element with the highest frequency.
- Finally, print the element with the highest frequency which will denote the mode of the list elements.
C++ Program to Find the Mode of a List
The following program demonstrates how we can find the mode of a list in C++.
C++
// C++ program to find the mode of a list
#include <iostream>
#include <list>
#include <unordered_map>
using namespace std;
int main()
{
// Initializing a list of integers
list<int> myList = { 1, 2, 3, 4, 5, 2, 2, 3, 4, 4, 4 };
// Creating a map to store the frequency of each element
unordered_map<int, int> mp;
// Iterating over the list and updating the frequency of
// elements
for (int num : myList) {
mp[num]++;
}
// Finding the maximum frequency from the map
int maxCount = 0, mode = 0;
for (auto it : mp) {
if (it.second > maxCount) {
maxCount = it.second;
mode = it.first;
}
}
// Printing the mode of the list
cout << "Mode of the list is : " << mode << endl;
return 0;
}
OutputMode of the list is : 4
Time Complexity: O(N), where N is the size of the list.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...