Majority Opinion is a compact problem with a powerful lesson: sometimes a global-looking condition can be detected by very small local patterns.
The local checks
The useful candidates are values that appear close enough together to become a local majority. The implementation checks two patterns:
- Two equal adjacent values:
h[i] == h[i + 1] - Two equal values with one value between them:
h[i] == h[i + 2]
If either pattern appears, mark that value as good.
for i from 0 to n - 2:
if h[i] == h[i + 1]:
good[h[i]] = true
if i + 2 < n and h[i] == h[i + 2]:
good[h[i]] = true
Why not test every subarray?
Testing all subarrays would be much slower and much more error-prone. The key insight is that any larger majority must reveal a short repeated pattern somewhere. That lets the solution focus on windows of size 2 and 3.
Output discipline
After marking good values, print them in increasing order. If none were marked, print -1. This is a place where students often solve the logic correctly but lose points on formatting.
Common mistakes
- Checking only adjacent duplicates and missing the
i,i + 2pattern. - Printing duplicates instead of marking values in a boolean array.
- Forgetting the no-answer case.
- Running the second check when
i + 2is out of bounds.
Practice prompt
For [1, 3, 1, 2, 2, 4], mark every value found by the two local checks. Then write the output exactly as the program should print it.
