Mode of Elements in Sorted Vector in C++
A number that occurs most frequently and has the highest frequency is considered a mode of the dataset. In this article, we will learn how to find the mode of all elements in a sorted vector of ints in C++.
Example
Input: myVector= {1,2,3,3,5,5,5,5,6,7}
Output: Mode is 5
Find the Mode of Vector Elements
To find a mode of all elements in a sorted vector, we can use the idea that the given vector is already sorted which means that the elements already occur in ascending order so we only need to see the maximum count until now and update it if it increases.
C++ Program to Find Mode in Vector of Integers in C++
The below program demonstrates how we can find a mode among elements in a sorted vector of ints in C++.
C++
// C++ Program to illustrate how to find the mode of the // elements in a sorted vector of ints #include <iostream> #include <vector> using namespace std; int main() { // Sorted vector of integers vector< int > a = { 1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5 }; int n = a.size(); int mode = a[0]; int curr_count = 1; int max_count = 1; // Iterate through the vector to find the mode for ( int i = 1; i < n; ++i) { if (a[i] == a[i - 1]) { // Increment the count if the current element is // equal to the previous one ++curr_count; } else { // Check if the count of the previous element is // greater than the maximum count if (curr_count > max_count) { max_count = curr_count; mode = a[i - 1]; } // Reset the count for the current element curr_count = 1; } } // Check the count of the last element if (curr_count > max_count) { mode = a[n - 1]; } // Display the mode if (mode != -1) { cout << "Mode is: " << mode << endl; } else { cout << "No mode found." << endl; } return 0; } |
Output
Mode is: 5
Time Complexity: O(N)
Auxiliary Space: O(1)