A sensor sends many readings. Each reading is a whole number from 0 to 100000. Print the reading that appears most often.
What to build
Read all the readings and count how many times each value appears in an array indexed by the value. Print the value with the highest count. If two values tie, print the smaller one.
Requirements
- Read until the input ends
- Count with an array of 100001 cells, not with nested loops
- On a tie, print the smaller value
Input
Up to 100,000 whole numbers, each from 0 to 100000, separated by spaces and newlines. There is at least one.
Output
The most common value, then a space, then how many times it appears.
Constraints
At most 100,000 numbers. An O(n²) solution is too slow.
Example
Input:
3 5 3 5 5 1
Output:
5 3
Why it works
A counting array turns each reading into one increment, so the whole job is O(n + 100000). Scanning the array from 0 upwards and replacing the best only when a count is strictly larger keeps the smaller value on a tie.
Examples
3 5 3 5 5 1
5 3
7
7 1
Hints
Hint 1
vector<int> cnt(100001, 0); then cnt[x]++ for every x.
Hint 2
Loop v from 0 to 100000 and keep the v with the biggest cnt[v].
Hint 3
Use cnt[v] > bestCount (strictly greater) so that ties keep the smaller value.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> cnt(100001, 0);
int x, top = 0;
while (cin >> x) {
cnt[x]++;
if (x > top) top = x;
}
int best = 0;
for (int v = 1; v <= top; v++)
if (cnt[v] > cnt[best]) best = v;
cout << best << " " << cnt[best] << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step