The Making File Names Unique problem asks you to simulate how operating systems handle duplicate file creations. You are given an array of strings representing folder names. If a name already exists, you must append a suffix (k) where k is the smallest positive integer such that the newly formed name name(k) does not already exist. You must return the array of assigned names.
This is a highly practical Hash Map problem. Interviewers ask it because it mimics real-world system behavior. It tests your ability to dynamically update and track state. The difficulty lies in the cascading effect: creating file(1) might conflict with an already existing file that was literally named file(1) by the user originally!
The problem is solved using a Hash Map for State Tracking. The map stores filename -> next_available_k.
When processing a name:
1. The assigned name is just name.k value. Enter a while loop: generate newName = name(k). Check if newName is in the map. If it is, increment k and try again.newName is found, update the original name's k in the map, and then insert newName into the map with a value of 1.Names: ["gta", "gta(1)", "gta", "avalon"]
"gta": Not in map. Assign "gta". Map: {"gta": 1}."gta(1)": Not in map. Assign "gta(1)". Map: {"gta": 1, "gta(1)": 1}."gta": In map! Current k is 1. We try "gta(1)".
"gta(1)" in map? Yes! So we increment k to 2."gta(2)". Is it in the map? No."gta(2)". Update map for "gta" to 3. Add "gta(2)" to map.{"gta": 3, "gta(1)": 1, "gta(2)": 1}."avalon": Not in map. Assign "avalon". Map: {..., "avalon": 1}.The biggest mistake is failing to insert the newly generated name(k) back into the Hash Map. If you process "gta" and generate "gta(1)", you MUST register "gta(1)" as a used name. If you don't, a subsequent user trying to explicitly create a file named "gta(1)" will not trigger a collision, resulting in duplicate files.
When tackling the Making File Names Unique interview pattern, rely heavily on String formatting tools specific to your language. Be careful with loop bounds; incrementing k inside a while (map.containsKey(newName)) loop is necessary, but ensure you save the incremented k back to the original base name's map entry so future collisions don't have to start searching from k=1 all over again (which would cause a Time Limit Exceeded error).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Evaluate the Bracket Pairs of a String | Medium | Solve | |
| Find Duplicate File in System | Medium | Solve | |
| Find and Replace Pattern | Medium | Solve | |
| Group Shifted Strings | Medium | Solve | |
| People Whose List of Favorite Companies Is Not a Subset of Another List | Medium | Solve |