Making File Names Unique — Leetcode 1487

Evangeline Liu
1 min readJan 12, 2023

--

Original problem link: https://leetcode.com/problems/making-file-names-unique/description/

In this problem, we’re given an array of names for folders that we want to create in a digital file system that may have repeats. For repeats, we have to append (k) to the repeat occurrences of the original name such that k is the first number where the file name will become unique. However, note that the array can also have something like

["a","a(1)","a"]

where (k) is part of the original name, as shown in the example above. Thus, we can keep a map of each name to the next available integer, but when we do need the next available integer, we need to check that “name(k)” is not already taken. Update the next available integer if needed.

Thus we come up with the following solution:

class Solution {
public String[] getFolderNames(String[] names) {
Map<String, Integer> map = new HashMap<>();
String[] result = new String[names.length];

for (int i = 0; i < names.length; i++) {
if (!map.containsKey(names[i])) {
map.put(names[i], 1);
result[i] = names[i];
} else {
int nextId = map.get(names[i]);
String next = names[i] + "(" + nextId + ")";

while (map.containsKey(next)) {
nextId++;
next = names[i] + "(" + nextId + ")";
}

map.put(next, 1);
map.put(names[i], nextId + 1);
result[i] = next;
}
}

return result;
}
}

The solution runs at about 47–48 ms and beats 84–87% of submissions.

--

--

No responses yet