S2Q2 · Most Frequent Numbers from Input¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: count frequencies, find the maximum frequency, collect all numbers with that frequency, print sorted.
n = int(input())
nums = [int(input()) for _ in range(n)]
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
max_freq = max(freq.values())
result = sorted(k for k, v in freq.items() if v == max_freq)
print(result)
Key rules: - One number per line after the first line - Find all numbers tied for the highest frequency - Print as a Python list in ascending order
Problem Statement¶
Problem (I/O type)
Read n numbers (one per line). Print a sorted list of all numbers that appear with the maximum frequency.
Example:
10
3
5
3
2
5
8
3
8
5
0
[3, 5]
Tracing the example¶
Numbers: [3, 5, 3, 2, 5, 8, 3, 8, 5, 0]
| Number | Count |
|---|---|
| 3 | 3 ← max |
| 5 | 3 ← max |
| 8 | 2 |
| 2 | 1 |
| 0 | 1 |
Max frequency = 3. Numbers with count 3: {3, 5}.
Sorted: [3, 5] → print as [3, 5] ✓
print(list) gives the bracket notation
print([3, 5]) outputs [3, 5] - exactly the required format. No need to manually format with brackets or join().
Solution approaches¶
from collections import Counter
n = int(input())
nums = [int(input()) for _ in range(n)]
freq = Counter(nums)
max_freq = max(freq.values())
result = sorted(k for k, v in freq.items() if v == max_freq)
print(result)
Counter builds the frequency map in one call. The rest of the logic is identical.
n = int(input())
nums = []
for _ in range(n):
nums.append(int(input()))
# Count frequencies
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
# Find max frequency
max_freq = 0
for count in freq.values():
if count > max_freq:
max_freq = count
# Collect all numbers with max frequency
result = []
for num, count in freq.items():
if count == max_freq:
result.append(num)
result.sort()
print(result)
from collections import Counter
n = int(input())
freq = Counter(int(input()) for _ in range(n))
max_freq = freq.most_common(1)[0][1] # frequency of the top element
result = sorted(k for k, v in freq.items() if v == max_freq)
print(result)
most_common(1)[0][1] gives the highest frequency without calling max() separately.
Key takeaways¶
Find max frequency first, then filter
Don't try to find the most frequent numbers in one pass. First compute all frequencies, then find the maximum, then collect all numbers matching that maximum. Two simple steps beat one complex one.
sorted() for ascending order
Dictionaries don't guarantee any order for ties. Always pass the result through sorted() to get ascending order before printing.
print(list) for bracket notation output
The required output is [3, 5] - exactly what print([3, 5]) produces. No manual formatting needed; Python's default list representation matches the expected output format.