DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Distant Barcodes

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:

import bisect

class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        n = len(barcodes)
        ctr = {}
        for b in barcodes:
            ctr[b] = ctr.get(b, 0) + 1
        freq = sorted([(-v, k) for k, v in ctr.items()])
        op = []
        while len(op) < n:
            i = 0
            curr = freq[i]
            if len(op) > 0:
                while curr[1] == op[-1]:
                    i += 1
                    curr = freq[i]
                c = curr[1]
            else:
                c = curr[1]
            op.append(c)
            del freq[bisect.bisect_left(freq, curr)]
            if curr[0] + 1 < 0:
                bisect.insort(freq, (curr[0] + 1, curr[1]))
        return op
Enter fullscreen mode Exit fullscreen mode

Top comments (0)