Distant Barcodes LeetCode solution in Java

1
class Solution {
2
public int[] rearrangeBarcodes(int[] barcodes) {
3

4
if (barcodes.length <= 2) {
5
return barcodes; // Problem says solution always exist.
6
}
7

8
Map<Integer, Integer> count = new HashMap<>();
9
Integer maxKey = null; // Character having max frequency
10

11
for (int i : barcodes) {
12
count.put(i, count.getOrDefault(i, 0) + 1);
13
if (maxKey == null || count.get(i) > count.get(maxKey)) {
14
maxKey = i;
15
}
16
}
17

18
int pos = 0;
19

20
// Fill maxChar
21
int curr = count.get(maxKey);
22
while (curr-- > 0) {
23
barcodes[pos] = maxKey;
24
pos += 2;
25
if (pos >= barcodes.length) {
26
pos = 1;
27
}
28
}
29

30
count.remove(maxKey); // Since that character is done, we don't need to fill it again
31

32
// Fill the remaining Characters.
33
for (int key : count.keySet()) {
34
curr = count.get(key);
35

36
while (curr-- > 0) {
37
barcodes[pos] = key;
38
pos += 2;
39
if (pos >= barcodes.length) {
40
pos = 1;
41
}
42
}
43
}
44

45
return barcodes;
46
}
47
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0