-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1054-distant-barcodes.js
More file actions
37 lines (32 loc) · 933 Bytes
/
1054-distant-barcodes.js
File metadata and controls
37 lines (32 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 1054. Distant Barcodes
* https://leetcode.com/problems/distant-barcodes/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number[]} barcodes
* @return {number[]}
*/
var rearrangeBarcodes = function(barcodes) {
const frequencyMap = new Map();
for (const code of barcodes) {
frequencyMap.set(code, (frequencyMap.get(code) || 0) + 1);
}
const sortedCodes = [...frequencyMap.entries()]
.sort((a, b) => b[1] - a[1]);
const result = new Array(barcodes.length);
let index = 0;
for (const [code, count] of sortedCodes) {
for (let i = 0; i < count; i++) {
if (index >= barcodes.length) index = 1;
result[index] = code;
index += 2;
}
}
return result;
};