Magicsheet logo

Making File Names Unique

Medium
75%
Updated 8/1/2025

Asked by 1 Company

Making File Names Unique

What is this problem about?

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.

Why is this asked in interviews?

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!

Algorithmic pattern used

The problem is solved using a Hash Map for State Tracking. The map stores filename -> next_available_k. When processing a name:

  1. If it's not in the map, add it with a value of 1. The assigned name is just name.
  2. If it IS in the map, retrieve its 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.
  3. Once a unique newName is found, update the original name's k in the map, and then insert newName into the map with a value of 1.

Example explanation

Names: ["gta", "gta(1)", "gta", "avalon"]

  1. "gta": Not in map. Assign "gta". Map: {"gta": 1}.
  2. "gta(1)": Not in map. Assign "gta(1)". Map: {"gta": 1, "gta(1)": 1}.
  3. "gta": In map! Current k is 1. We try "gta(1)".
    • Is "gta(1)" in map? Yes! So we increment k to 2.
    • We try "gta(2)". Is it in the map? No.
    • Assign "gta(2)". Update map for "gta" to 3. Add "gta(2)" to map.
    • Map: {"gta": 3, "gta(1)": 1, "gta(2)": 1}.
  4. "avalon": Not in map. Assign "avalon". Map: {..., "avalon": 1}.

Common mistakes candidates make

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.

Interview preparation tip

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).

Similar Questions