Warehouse Barcode Organization Challenge

In a busy warehouse, you have a row of barcodes represented by an array barcodes[], where barcodes[i] is the value of the i-th barcode. Your task is to rearrange these barcodes so that no two adjacent barcodes have the same value.

Think of it like organizing products on a shelf - you want to avoid having identical items next to each other for better inventory management and visual appeal.

Goal: Return any valid rearrangement where no adjacent elements are equal.
Guarantee: A valid solution always exists for the given input.

Input & Output

example_1.py โ€” Basic Case
$ Input: barcodes = [1,1,1,2,2,2]
โ€บ Output: [1,2,1,2,1,2]
๐Ÿ’ก Note: We have 3 ones and 3 twos. By alternating them, we ensure no adjacent barcodes are the same.
example_2.py โ€” Uneven Distribution
$ Input: barcodes = [1,1,1,1,2,2,3,3]
โ€บ Output: [1,2,1,3,1,2,1,3]
๐Ÿ’ก Note: Element 1 appears 4 times, while 2 and 3 appear 2 times each. We place 1s first, then fill with 2s and 3s to avoid adjacency.
example_3.py โ€” Single Element Type
$ Input: barcodes = [1,2,3,4,5]
โ€บ Output: [1,2,3,4,5]
๐Ÿ’ก Note: All elements are unique, so any arrangement works. The original order already satisfies the constraint.

Constraints

  • 1 โ‰ค barcodes.length โ‰ค 104
  • 1 โ‰ค barcodes[i] โ‰ค 104
  • A valid solution is guaranteed to exist
  • The frequency of the most common element is at most โŒˆn/2โŒ‰

Visualization

Tap to expand
Warehouse Barcode OrganizationInitial Inventory CountProduct ACount: 4Product BCount: 3Product CCount: 2Priority Queue (Most Frequent First)A:4B:3C:2Shelf Arrangement ProcessStep 1: Place most frequent (A)AStep 2: Can't place A again (adjacent)Place next most frequent (B)ABContinue pattern...Final Optimal ArrangementABACABACBโœ“ No Adjacent Duplicates!๐ŸŽฏ Key Insight: Always prioritize the most abundant item, but temporarily skip it if it would create adjacent duplicates
Understanding the Visualization
1
Count Inventory
First, count how many of each product type we have
2
Prioritize by Quantity
Always try to place the most abundant product next
3
Avoid Adjacent Duplicates
If placing the most abundant would create adjacency, pick the next most abundant
4
Update and Continue
Reduce the count of placed item and continue until all items are arranged
Key Takeaway
๐ŸŽฏ Key Insight: The greedy approach works because we always handle the most constrained items first - those with highest frequency that are hardest to place without creating adjacent pairs.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
47.2K Views
Medium-High Frequency
~25 min Avg. Time
1.6K 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