Distant Barcodes - Problem
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Input & Output
Example 1 — Basic Case
$
Input:
barcodes = [1,1,2,2,3,2]
›
Output:
[2,1,2,1,2,3]
💡 Note:
Rearrange so no adjacent elements are equal. We place the most frequent element (2) in alternating positions, then fill remaining spots with other elements.
Example 2 — Minimum Size
$
Input:
barcodes = [1,2]
›
Output:
[1,2]
💡 Note:
Already arranged correctly - no two adjacent elements are the same.
Example 3 — All Same Frequency
$
Input:
barcodes = [1,2,3,1,2,3]
›
Output:
[1,2,1,3,2,3]
💡 Note:
When all elements have same frequency, any valid alternating arrangement works.
Constraints
- 1 ≤ barcodes.length ≤ 104
- 1 ≤ barcodes[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Original barcodes with potential adjacent duplicates
2
Frequency Analysis
Count how often each barcode appears
3
Rearranged Output
No two adjacent barcodes are the same
Key Takeaway
🎯 Key Insight: Place the most frequent elements in alternating positions to prevent adjacent duplicates while using all elements efficiently.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code