Distant Barcodes Problem
Description
LeetCode Problem 1054.
In a warehouse, there is a row of barcodes, where the i^th 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 <= 100001 <= barcodes[i] <= 10000
Solution
Approach: Count, Sort and Fill Every Other Slot
Sort the barcodes so the most frequent value comes first, ties broken by value. This keeps equal barcodes next to each other in the sorted order. Then write the sorted list into the answer in two sweeps: first the even indices 0, 2, 4, ..., then the odd indices 1, 3, 5, ....
Why no two neighbours end up equal: let h = ceil(n / 2) be the number of even slots. Index 2a gets item a of the sorted list and index 2a + 1 gets item h + a, so two neighbours in the answer are h or h - 1 places apart in the sorted list. Since equal barcodes form one block in that list, two equal neighbours would need a value with at least h copies. Because an answer is guaranteed, no value has more than h copies, and a value with exactly h copies is a most frequent one, so it is sorted first and fills only even slots. (If n is even and two values both have n / 2 copies, the second one fills exactly the odd slots.)
The answer is not unique; any arrangement with no equal neighbours is accepted.
Complexity: O(n log n) time for the sort and O(n) extra space.
from collections import Counter
class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
cnt = Counter(barcodes)
# Most frequent first; equal counts by value, so equal barcodes stay together.
barcodes.sort(key=lambda x: (-cnt[x], x))
n = len(barcodes)
ans = [0] * n
half = (n + 1) // 2
ans[::2] = barcodes[:half] # first half on the even indices 0, 2, 4, ...
ans[1::2] = barcodes[half:] # the rest on the odd indices 1, 3, 5, ...
return ans