How to Find the Mode of Numbers in an Array in C++?
Mode of any dataset is the item that occurs most frequently in it. In this article, we will find the mode of numbers in an unsorted array in C++.
For Example,
Input: myArray = { 1, 2, 3, 4, 5, 2, 3, 2, 2, 4, 2 } Output: Mode : 2
Finding Mode of Array Elements in C++
To find the mode of the array elements, we need to count the frequency of all elements in the array. To do that, we can use the std::unordered_map container where the key will represent the array element and its value will represent its frequency.
Approach
- Create an unordered_map of <int, int>.
- Start traversing the array.
- Now, if the array element is present in the unordered_map, increment its value.
- If the array element is not present, add the array element as key with value 1.
- Finally, use std::max_element algorithm to find the maximum frequency and hence mode of the numbers.
C++ Program to Find Mode of Array Elements
C++
// C++ program to find the mode of an array #include <algorithm> #include <iostream> #include <unordered_map> using namespace std; // Function to find the mode of an array int findMode( int arr[], int n) { // Create a frequency map to count occurrences of each // element unordered_map< int , int > freqMap; for ( int i = 0; i < n; i++) { freqMap[arr[i]]++; } // Find the element with the maximum frequency auto maxElement = max_element(freqMap.begin(), freqMap.end(), []( const auto & a, const auto & b) { return a.second < b.second; }); // Return the mode (element with maximum frequency) return maxElement->first; } int main() { // Test array int arr[] = { 2, 2, 3, 3, 3, 4 }; int n = sizeof (arr) / sizeof (arr[0]); // Find and print the mode of the array cout << "Mode of the array is " << findMode(arr, n) << endl; return 0; } |
Output
Mode of the array is 3
Time Complexity: O(n)
Auxiliary Space: O(n)