Member-only story
Leetcode 1487: Making File Names Unique
2 min readJun 24, 2020
In this Leetcode problem, we try to name files in a file system in a unique way using a particular algorithm:
Solution
A couple of ideas to obtain the solution:
- Maintain
next
mapString
toInteger
that stores the next smallest (potential) positive number to use for the particularString
key. - Maintain a set of strings
used
of all the strings used so far. We use it to make sure every string added is unique. - We create array
res
to store the results to return. - For each new name, we check if the key is used, then if needed check what needs to be appended, then we append it and add it to res, maintaining all the data structures at the same time.
Here is the full code:
class Solution {
public String[] getFolderNames(String[] names) {
int n = names.length;
// Next free int for prefix
Map<String, Integer> next = new HashMap<>();
// Exact set of used names
Set<String> used = new HashSet<>();
// Result to return
String[] res = new String[n];
for (int i = 0; i < n; i++) {
String name = names[i];
if (used.contains(name)) {
if (!next.containsKey(name)) {
next.put(name, 1)…