LeetCode 1487: Making File Names Unique Solution
Master LeetCode problem 1487 (Making File Names Unique), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1487. Making File Names Unique
Problem Explanation
Explanation:
- We can iterate through the array of names and keep track of the count of each name encountered so far.
- If a name is encountered for the first time, we add it as it is to the result array.
- If a name has been encountered before, we append a suffix in the form of (k) to make it unique, where k is the smallest positive integer that makes the name unique.
Time complexity: O(n), where n is the number of names in the input array. Space complexity: O(n) for storing the result array.
Solution Code
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])) {
result[i] = names[i];
map.put(names[i], 1);
} else {
int count = map.get(names[i]);
String newName = names[i] + "(" + count + ")";
while (map.containsKey(newName)) {
count++;
newName = names[i] + "(" + count + ")";
}
result[i] = newName;
map.put(names[i], count + 1);
map.put(newName, 1);
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1487 (Making File Names Unique)?
This page provides optimized solutions for LeetCode problem 1487 (Making File Names Unique) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1487 (Making File Names Unique)?
The time complexity for LeetCode 1487 (Making File Names Unique) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1487 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1487 in Java, C++, or Python.