#1054
Medium Algorithms Distant barcodes
Array Hash Table Greedy Sorting Heap (Priority Queue) Counting
48.6% acceptance
Feb 25, 2026
1347
52
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn rearrange_barcodes(barcodes: Vec<i32>) -> Vec<i32> {
let n = barcodes.len();
let mut freq: std::collections::HashMap<i32, usize> = std::collections::HashMap::new();
for &b in &barcodes { *freq.entry(b).or_insert(0) += 1; }
let mut sorted: Vec<(usize, i32)> = freq.into_iter().map(|(k,v)| (v,k)).collect();
sorted.sort_unstable_by(|a,b| b.cmp(a));
let mut res = vec![0i32; n];
let mut idx = 0usize;
for (cnt, val) in sorted {
for _ in 0..cnt {
if idx >= n { idx = 1; }
res[idx] = val;
idx += 2;
}
}
res
}
}