Determine whether an array can be rearranged so that no two adjacent elements are equal.
You are given an array of integers. Decide whether it is possible to reorder the elements so that every pair of neighboring elements in the resulting array contains different values.
In other words, after rearranging the array, there should be no index such that .
Return whether such a permutation exists.
Input Format
- The first line contains an integer — the size of the array.
- The second line contains integers describing the array.
Output Format
- Print
YESif the array can be rearranged so that no two adjacent elements are equal. - Otherwise, print
NO.
Constraints
- The array contains integers.
- The exact original contest limits are not assumed here; solve using the standard frequency-based condition.
Example 1
Input
5 1 1 2 2 3
Output
YES
Explanation
One valid rearrangement is 1 2 1 3 2, where no adjacent elements are equal.
Example 2
Input
4 7 7 7 1
Output
NO
Explanation
The value 7 appears 3 times out of 4, so it cannot be placed without two 7s becoming adjacent.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.