I'm trying to write a program, in which the user gives n numbers and the program has to find out which number is being repeated the most. for example for numbers : 4 5 5 1 3 1 1 7 1 the answer is 1 I'm a beginner by the way, so that's why most of the answers which were already on the site didn't suit me. I'd be very thankful.
-
OMG, search StackOverflow first: "c++ find mode" – Thomas Matthews Dec 01 '14 at 20:27
-
1Either show your code, and describe the specific issue or this will be closed as a duplicate of http://stackoverflow.com/questions/9316352/how-do-i-find-the-mode-of-an-array – Thomas Matthews Dec 01 '14 at 20:29
-
@ThomasMatthews: That question asks about a sorted array, and I've adjusted its title to reflect that. – Benjamin Lindley Dec 01 '14 at 20:41
-
So, I didn't list all the results from the search: https://www.google.com/search?q=stackoverflow+c%2B%2B+find+mode&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a&channel=sb – Thomas Matthews Dec 01 '14 at 20:50
-
@Sara, you might want to use a `std::vector` as per my answer. – Andreas DM Dec 01 '14 at 21:26
3 Answers
Use a hashmap (unordered_map
) to count the occurrences of the numbers, then search the maximum occurrence count in the hashmap.

- 5,487
- 2
- 23
- 52
-
1The overhead of hashing is not required here; an `std::map` would suffice. – cdhowie Dec 01 '14 at 20:40
-
Using a std::map increases the algorithmic complexity to O(n log n), whereas using a hashmap is O(n). n O(1) inserts and one O(n) search vs n O(log n) inserts. Have you ensured, that insertion into std::map is faster than into std::unordered_map? – midor Dec 01 '14 at 20:45
I think that you can use a priority queue it will holds the elements {1,1,1,1,3,4,5,5,7} and then manipulate the mode from this queue

- 5
- 3
What you probably would want to do is insert the numbers into a std::vector
, use std::sort
(in <algorithm>
) on it, and loop through it so see which number occurs the most times.
To give you an idea, you may use std::vector<int>::iterator
while looping (use auto
instead) to point to the beginning + 1 of the vector, then check if the value to which the iterator points is equals to
iterator - 1
. If the current value is higher than max value then store it, along with an iterator to that object.
Hope that helps you on the way.

- 10,685
- 6
- 35
- 62