#C1929. Rearrange Array to Avoid Adjacent Duplicates
Rearrange Array to Avoid Adjacent Duplicates
Rearrange Array to Avoid Adjacent Duplicates
You are given a list of integers. Your task is to rearrange the list such that no two identical elements are adjacent. If it is impossible to rearrange the list to satisfy this condition, output an empty list.
Formally, given a list \( nums \) of integers, rearrange the elements so that for every \( i \) (\(1 \le i < n\)), the condition \( nums[i] \neq nums[i+1] \) holds, where \( n \) is the length of the list. If multiple valid rearrangements exist, you may output any one of them. If no valid rearrangement exists, output []
.
Example:
Input: 1 1 2 3 3 Output: 1 3 1 2 3
Note: In the above example, the output is one possible valid rearrangement. The condition is that no two consecutive numbers are identical.
inputFormat
The input is read from stdin
as a sequence of space-separated integers. The list may be empty. All the integers belong to the range of 32-bit signed integers.
Example: 1 1 2 3 3
outputFormat
Output the rearranged list to stdout
as a sequence of space-separated integers in one line. If no valid rearrangement exists, output []
.
1 1 2 3 3
1 3 1 2 3