Leetcode 1487: Making File Names Unique

grid47
grid47
Exploring patterns and algorithms
Jun 11, 2024 6 min read

You are given an array ’names’ where each element represents a folder name. You will create folders sequentially at each minute. If a folder with the same name already exists, a suffix of the form ‘(k)’ is added, where k is the smallest positive integer such that the resulting name is unique.
Problem
Approach
Steps
Complexity
Input: An array of strings 'names' of size n, where each string represents a folder name.
Example: names = ["doc", "doc", "img", "doc(1)"]
Constraints:
• 1 <= names.length <= 5 * 10^4
• 1 <= names[i].length <= 20
• names[i] consists of lowercase English letters, digits, and/or round brackets.
Output: Return an array of strings where each string is the folder name assigned by the system after the respective minute.
Example: Output: ["doc", "doc(1)", "img", "doc(1)(1)"]
Constraints:
• The returned list must contain n strings, one for each folder name assigned.
Goal: Create folder names in such a way that they are unique by appending the smallest integer k to the name if necessary.
Steps:
• 1. Initialize a dictionary to track the frequency of folder names.
• 2. Iterate over the 'names' array.
• 3. If the folder name is already in the dictionary, append '(k)' where k is the smallest integer that makes the name unique.
• 4. Update the dictionary with the new name and continue.
Goal: Handle all edge cases where folder names repeat or when the list is very large.
Steps:
• The input size can be large, so the solution must be efficient.
• The folder names can include digits and brackets.
Assumptions:
• The folder names are case-sensitive.
• The suffix '(k)' is always appended to the original name in case of a conflict.
Input: names = ["doc", "doc", "img", "doc(1)"]
Explanation: The first 'doc' is assigned as 'doc', the second 'doc' gets a suffix '(1)', and so on.

Input: names = ["file", "file", "file", "image"]
Explanation: The first 'file' is assigned as 'file', the second gets '(1)', the third gets '(2)', and 'image' remains 'image'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus