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
Distant Barcodes Problem OverviewInput: [1,1,2,2,3,2] - Adjacent duplicates present112232❌ Adjacent 1s❌ Adjacent 2sOutput: [2,1,2,1,2,3] - No adjacent duplicates!212123✓ Different✓ Different
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.
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 12
32.0K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen