![]() |
VOOZH | about |
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.
Examples:
Input: barcodes = {1, 1, 1, 2, 2, 2}
Output: {2, 1, 2, 1, 2, 1}
Explanation: In {2, 1, 2, 1, 2, 1}, no two adjacent barcodes are equal.Input: barcodes = {1, 1, 1, 1, 2, 2, 3, 3}
Output: {1, 3, 1, 3, 1, 2, 1, 2}
Explanation: In {1, 3, 1, 3, 1, 2, 1, 2}, no two adjacent barcodes are equal.
Approach: To solve the problem, follow the below idea:
The idea is to first use the map to get the frequency of characters. Then add them all into a heap , and if possible each iteration in while loop , pop out 2 elements from the heap. We have to pop out 2 elements because in case we just pop out one and put back in the heap, then there is a chance that the same element is still occurring the most number of times and hence it will become adjacent. so pop out 2 at a time to avoid this.
Step-by-step algorithm:
Below is the implementation of the algorithm:
Rearranged barcodes: 2 1 2 1 2 1
Time complexity: O(n log m), where n is the size of the input vector and m is the number of unique barcodes.
Auxiliary space: O(m + n), where m is the number of unique barcodes and n is the size of the input vector.