Distant Barcodes — LeetCode 1054 Python Solution

MediumGreedyArrayHash TableCountingSortingHeap (Priority Queue)
Problem
#1054
Reading time
2 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        cnt = Counter(barcodes)
        barcodes.sort(key=lambda x: (-cnt[x], x))
        n = len(barcodes)
        ans = [0] * len(barcodes)
        ans[::2] = barcodes[: (n + 1) // 2]
        ans[1::2] = barcodes[(n + 1) // 2 :]
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(M) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1054. Distant Barcodes is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1054. Distant Barcodes?
LeetCode 1054. Distant Barcodes is rated Medium on LeetCode.
What is the time complexity of LeetCode 1054. Distant Barcodes?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1054. Distant Barcodes?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 1054. Distant Barcodes cover?
LeetCode 1054. Distant Barcodes is tagged Greedy, Array, Hash Table, Counting, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview