MediumNo. 1487

Making File Names Unique — LeetCode 1487 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
2 min

The 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].

Example

Input
names = ["pes","fifa","gta","pes(2019)"]
Output
["pes","fifa","gta","pes(2019)"]
Explanation
Let's see how the file system creates folder names:

Python solution

PythonSolution
class Solution:
    def getFolderNames(self, names: List[str]) -> List[str]:
        d = defaultdict(int)
        for i, name in enumerate(names):
            if name in d:
                k = d[name]
                while f'{name}({k})' in d:
                    k += 1
                d[name] = k + 1
                names[i] = f'{name}({k})'
            d[names[i]] = 1
        return names

Complexity

Time
O(n)
Space · auxiliary
O(L)where L is the sum of the lengths of all file names in the names array

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1487. Making File Names Unique is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy
0522Longest Uncommon Subsequence IIMedium

Frequently asked questions

How hard is LeetCode 1487. Making File Names Unique?

LeetCode 1487. Making File Names Unique is rated Medium on LeetCode.

What is the time complexity of LeetCode 1487. Making File Names Unique?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1487. Making File Names Unique?

The Python solution on this page uses O(L), where L is the sum of the lengths of all file names in the names array auxiliary space.

What topics does LeetCode 1487. Making File Names Unique cover?

LeetCode 1487. Making File Names Unique is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.