Open In App

How to Find the Mode in a 2D Array in C++?

A mode is a number that occurs most frequently in comparison to other numbers in a given dataset. In this article, we will find the mode in a 2D array of integers in C++.

Input:
myArray = { {1, 2, 2, 3},
{3, 4, 5, 5},
{5, 6, 7, 8} }

Output: 5

Mode in 2D Array

To find a mode of numbers in a 2D array, we can use the unordered_map to keep the count of the frequency of the elements.



Example

The below example demonstrates the use of map to find multiple modes if exist in a 2D array.






// C++ program to find the mode of a 2D array
#include <iostream>
#include <unordered_map>
  
using namespace std;
  
// Function to find the mode of a 2D array
int findMode(int arr[][4], int rows)
{
    unordered_map<int, int> freq;
  
    // Count the frequency of each number in the array
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < 4; ++j) {
            freq[arr[i][j]]++;
        }
    }
  
    // Find the number with the highest frequency (mode)
    int mode = arr[0][0];
    int maxCount = 0;
    for (auto it = freq.begin(); it != freq.end(); ++it) {
        if (it->second > maxCount) {
            maxCount = it->second;
            mode = it->first;
        }
    }
  
    return mode;
}
  
int main()
{
    // Example 2D array
    int arr[3][4] = { { 1, 2, 2, 3 },
                      { 3, 4, 5, 5 },
                      { 5, 6, 7, 8 } };
  
    // Find and display the mode of the array
    cout << "Mode: " << findMode(arr, 3) << endl;
  
    return 0;
}

Output
Mode: 5

Time Complexity: O(N * M)
Auxiliary Space: O(N * M)

We can also create a max pair that keeps the element and count of the currently maximum encountered value. But it may fail if there are multiple modes.


Article Tags :