#1487
Medium Algorithms Making file names unique
Array Hash Table String
38.4% acceptance
Feb 25, 2026
464
741
Given an array of strings names of size n. You will create n folders in your file system such that,
at the ith minute, you will create a folder with the name names[i].
Since two files cannot have the same name, if you enter a folder name that was previously used,
the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer
such that the obtained name remains unique.
Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn get_folder_names(names: Vec<String>) -> Vec<String> {
let mut used: HashMap<String, u32> = HashMap::new();
let mut result = Vec::with_capacity(names.len());
for name in names {
if !used.contains_key(&name) {
used.insert(name.clone(), 1);
result.push(name);
} else {
let mut k = *used.get(&name).unwrap();
loop {
let candidate = format!("{}({})", name, k);
k += 1;
if !used.contains_key(&candidate) {
*used.get_mut(&name).unwrap() = k;
used.insert(candidate.clone(), 1);
result.push(candidate);
break;
}
}
}
}
result
}
}