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 Unique INPUT names array (n=4) [0] "pes" [1] "fifa" [2] "gta" [3] "pes(2023)" HashMap Structure Key: name string Value: next suffix (k) ALGORITHM STEPS 1 Initialize HashMap Empty map to track names 2 Process each name Check if name exists in map 3 Handle duplicates Add (k) suffix if needed 4 Update HashMap Store name with next k HashMap State (Final): "pes" --> 1 "fifa" --> 1 "gta" --> 1 "pes(2023)"--> 1 FINAL RESULT Output array (ans) [0] "pes" OK [1] "fifa" OK [2] "gta" OK [3] "pes(2023)" OK All names unique! No conflicts found in this example - all names were already distinct Key Insight: Use a HashMap to track each name with its next available suffix (k). When a name exists, increment k until name(k) is unique. Store both original and suffixed names in the map to handle cases like "pes(2023)" which might conflict with auto-generated "pes(2023)". TutorialsPoint - Making File Names Unique | Hash Map - Track Used Names
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