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 <= 100001 <= barcodes[i] <= 10000This approach leverages a priority queue to ensure that the most frequent barcodes are spaced apart. By sorting the barcodes by frequency, we can fill in the positions, alternating between the most available barcodes to handle the adjacency constraint efficiently.
This Python implementation uses the collections.Counter to count the frequencies of each barcode type. A max heap (priority queue) is utilized to always extract the barcode with the highest frequency first, and we keep track of the last processed barcode to avoid immediate reuse.
Java
Time Complexity: O(n log k), where n is the number of barcodes and k is the number of unique barcodes.
Space Complexity: O(n + k), for the heap and Counter storage.
In this approach, the barcodes are first sorted by frequency, then they are placed alternately in even and odd indices within the result array. This method efficiently arranges the barcodes such that no two adjacent barcodes are equal.
This C++ implementation first counts the occurrences of each barcode type. It sorts the barcodes based on frequency and then arranges them by filling even indices first, followed by odd indices. This ensures an alternating pattern that prevents adjacent duplicates.
JavaScript
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(n), for storing results and map.
| Approach | Complexity |
|---|---|
| Greedy PriorityQueue Approach | Time Complexity: O(n log k), where n is the number of barcodes and k is the number of unique barcodes. |
| Index Filling Approach | Time Complexity: O(n log n), due to sorting. |
How many LeetCode problems should you solve? #leetcode #techinterview #developer #softwareengineer • CrioDo • 304,617 views views
Watch 9 more video solutions →Practice Distant Barcodes with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor