In a warehouse, a row of barcodes is given as an integer array where barcodes[i] is the i-th barcode value. Rearrange the barcodes so that no two adjacent barcodes are equal.
A valid answer is guaranteed to exist. Return any arrangement that satisfies the rule.
Example 1
Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Alternating the two values keeps equal barcodes from touching.
Example 2
Input: barcodes = [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,1,2,1,2]
The value 1 is most frequent, so it takes alternating slots first, then the rest fill in without repeats.
Constraints
1 <= barcodes.length <= 10^41 <= barcodes[i] <= 10^4A valid answer always exists.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI