Making File Names Unique - Problem

Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].

Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where k is the smallest positive integer such that the obtained name remains unique.

Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.

Input & Output

Example 1 — Basic Duplicates
$ Input: names = ["pes","fifa","gta","pes(2023)"]
Output: ["pes","fifa","gta","pes(2023)"]
💡 Note: All names are unique, so no modifications needed. The system assigns exact names as requested.
Example 2 — Multiple Duplicates
$ Input: names = ["gta","gta(1)","gta","avalon"]
Output: ["gta","gta(1)","gta(2)","avalon"]
💡 Note: First 'gta' is unique. 'gta(1)' is unique. Second 'gta' conflicts with first, so becomes 'gta(2)' (since 'gta(1)' exists). 'avalon' is unique.
Example 3 — Sequential Conflicts
$ Input: names = ["kaido","kaido(1)","kaido","kaido(1)"]
Output: ["kaido","kaido(1)","kaido(2)","kaido(1)(1)"]
💡 Note: First 'kaido' is unique. 'kaido(1)' is unique. Second 'kaido' becomes 'kaido(2)'. Second 'kaido(1)' becomes 'kaido(1)(1)'.

Constraints

  • 1 ≤ names.length ≤ 5 × 104
  • 1 ≤ names[i].length ≤ 20
  • names[i] consists of lower case English letters, digits, and/or round brackets.

Visualization

Tap to expand
Making File Names UniqueInput Names:pesfifagtapesSystem processes each name...Unique Names:pesfifagtapes(1)✓ Unique✓ Unique✓ UniqueAdded (1)Output: ["pes", "fifa", "gta", "pes(1)"]
Understanding the Visualization
1
Input
Array of requested file names
2
Process
Add suffix (k) to duplicates where k is smallest available
3
Output
Array of actual unique file names
Key Takeaway
🎯 Key Insight: Use a hash map to track the next available suffix number for each base name, avoiding redundant conflict checks
Asked in
Amazon 15 Facebook 12
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen