1487. Making File Names Unique
UnknownView on LeetCode
Time: O(n·m)
Space: O(n·m)
Advertisement
Approach
Dictionary tracks the next suffix to try for each name; increment suffix until a fresh name is found.
Key Techniques
Hash Table
Hash tables provide O(1) average-case lookup, insert, and delete. They are the go-to tool for counting frequencies, detecting complements (Two Sum pattern), and caching seen values. In C#, use Dictionary<K,V> for maps and HashSet<T> for membership checks.
String
String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.
1487.cs
C#
// Approach: Dictionary tracks the next suffix to try for each name; increment suffix until a fresh name is found.
// Time: O(n·m) Space: O(n·m)
public class Solution
{
public string[] GetFolderNames(string[] names)
{
string[] ans = new string[names.Length];
Dictionary<string, int> nameToSuffix = new Dictionary<string, int>();
for (int i = 0; i < names.Length; ++i)
{
string name = names[i];
if (nameToSuffix.ContainsKey(name))
{
int suffix = nameToSuffix[name];
string newName = GetName(name, ++suffix);
while (nameToSuffix.ContainsKey(newName))
newName = GetName(name, ++suffix);
nameToSuffix[name] = suffix;
nameToSuffix[newName] = 0;
ans[i] = newName;
}
else
{
nameToSuffix[name] = 0;
ans[i] = name;
}
}
return ans;
}
private string GetName(string name, int suffix)
{
return name + "(" + suffix.ToString() + ")";
}
}Advertisement
Was this solution helpful?