LeetCode 1054. Distant Barcodes Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1054. Distant Barcodes

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

Solutions

Solution 1: Counting + Sorting

First, we use a hash table or array cnt to count the number of occurrences of each number in the array barcodes. Then, we sort the numbers in barcodes according to their occurrence times in cnt from large to small. If the occurrence times are the same, we sort them from small to large (to ensure the same numbers are adjacent).

Next, we create an answer array ans of length n. We traverse the sorted barcodes, and sequentially fill the elements into the even index positions 0, 2, 4, … of the answer array. Then, we fill the remaining elements into the odd index positions 1, 3, 5, … of the answer array.

The time complexity is O(n × log n), and the space complexity is O(M). Where n and M are the length of the array barcodes and the maximum value in the array barcodes, respectively.

PythonJavaC++GoTypeScript
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !