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 INPUT Original Barcodes Array 1 1 2 2 3 2 0 1 2 3 4 5 Frequency Count: 1: 2 2: 3 3: 1 Input: [1,1,2,2,3,2] Goal: No adjacent barcodes equal ALGORITHM STEPS 1 Count Frequencies Count occurrences of each barcode value 2 Build Max Heap Sort by frequency (highest first) 2:3 1:2 3:1 3 Place Elements Take top 2 from heap, place alternately 4 Reinsert to Heap Decrement count, reinsert if count > 0 FINAL RESULT Rearranged Barcodes 2 1 2 1 2 3 0 1 2 3 4 5 Verification: 2 != 1 - OK 1 != 2 - OK 2 != 1 - OK 1 != 2 - OK 2 != 3 - OK All Adjacent Pairs Are Different - OK Output: [2,1,2,1,2,3] Key Insight: Use a Max Heap (Priority Queue) to always place the most frequent element first. By alternating between the two most frequent elements, we ensure no adjacent duplicates. The greedy approach works because placing high-frequency elements early spreads them out across the array. TutorialsPoint - Distant Barcodes | Optimal Solution (Max Heap Approach)
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