Talentd
FleetCode

1054. Distant Barcodes

Medium49.3% acceptance2 companies

In a warehouse, there is a row of barcodes, where the ith 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.

Example 1:

Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

Example 2:

Input: barcodes = [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,1,2,1,2]

Constraints:

  • 1 <= barcodes.length <= 10000
  • 1 <= barcodes[i] <= 10000

Asked at 2 companies

Hints open one at a time

Hint 1
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
6:51
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,1,1,2,2,2]
Input
[1,1,1,1,2,2,3,3]
Your code is saved on this device.Solution