Distant Barcodes
1 approach, code in every language
Problem description
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.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free