Skip to content

1054. Distant Barcodes

Difficulty Topics

Description

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

Solution

distant-barcodes.py
class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        counter = collections.Counter(barcodes)
        count = sorted([(counter[x], x) for x in counter], key = lambda x : -x[0])
        i = 0
        n = len(barcodes)
        res = [None] * n

        for cnt,key in count:
            for _ in range(cnt):
                if i >= n: i = 1
                res[i] = key
                i += 2

        return res