Python 1487.py
class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
prefix = defaultdict(int)
for n in names:
# new name (maybe it's the old if not used yet)
filename = n
# increment counter until there is no collision
while filename in prefix:
filename = n + "(" + str(prefix[n]) + ")"
prefix[n] += 1
# block that filename from further usage
prefix[filename] = 1
yield filename
Difficulty
and has an acceptance rate of about 39% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a generator-based algorithm that produces a sequence of unique folder names from an input list. It follows the convention that when a name collides with a previously generated one, a numeric suffix in parentheses is appended, incrementing the number until the name becomes unique. The implementation relies on a hash-based dictionary to track used names and the next suffix to try for each base name.
Core Data Structure
The algorithm initializes a defaultdict of integers named prefix. This dictionary serves two purposes: it records every name that has already been emitted, and it stores the next numeric suffix to attempt for each original name. Because defaultdict returns 0 for missing keys, the code can safely read and update counters without explicit existence checks.
prefix = defaultdict(int)
Main Loop
The outer for loop iterates over each candidate name in the input list names. For each iteration, a temporary variable filename is set to the original candidate. This variable will be mutated only if a collision is detected.
for n in names:
filename = n
Collision Detection and Resolution
A while loop checks whether the current filename already exists as a key in prefix. If it does, the algorithm constructs a new candidate by appending a suffix consisting of an opening parenthesis, the current counter value for the base name n, and a closing parenthesis. After forming the new candidate, the counter for the base name is incremented, preparing the next suffix value for any future collision involving the same base name.
while filename in prefix:
filename = n + "(" + str(prefix[n]) + ")"
prefix[n] += 1
The loop continues until a filename is found that is not present in prefix, guaranteeing uniqueness at that point.
Registration of the New Name
Once a unique filename is identified, it is recorded in prefix with a dummy value of 1. This entry blocks the name from being reused in later iterations, whether it originated as an original input or as a generated suffixed name. The method then yields the unique name to the caller.
prefix[filename] = 1
yield filename
Edge Cases Handled
The algorithm naturally accommodates several edge conditions:
-
Repeated Original Names - When the same raw name appears multiple times, the first occurrence is emitted unchanged, and subsequent occurrences receive incremented suffixes such as
(0),(1), etc., because the counter for that base name starts at0and is increased after each collision. -
Names Already Containing Parentheses - If an input name already includes a parenthetical suffix (e.g.,
"file(1)"), the algorithm treats the entire string as a distinct key. Collisions are resolved by appending an additional suffix, resulting in names like"file(1)(0)", preserving the original structure. -
Empty Input List - An empty
nameslist leads to the generator producing no output, as the outer loop never executes. -
Large Number of Collisions for a Single Base - The counter stored in
prefix[n]ensures that the algorithm does not restart from0after each collision; it continues from the last used suffix, preventing unnecessary repeated checks.
Performance Optimizations
The design leverages constant-time dictionary operations for both existence checks and counter updates, which keeps the overall processing time proportional to the number of input names and collisions. By storing the next suffix to try (prefix[n]) directly alongside each base name, the algorithm avoids scanning previously generated names or recomputing suffixes from scratch. This approach reduces the number of string concatenations required when many collisions occur for the same base name.
Additionally, the use of a generator (yield) allows the caller to consume results lazily, which can be advantageous when only a subset of the output is needed or when the caller processes names incrementally. This lazy evaluation avoids the overhead of constructing an intermediate list of all results before they are used.
ELI5 - Simplified Explanation
Imagine having a special box where you put labels on your toys so they do not get mixed up. This code helps you name your toys when you have too many with the same name.
First, it looks at the list of names you want to use. If a name has never been seen before, it keeps that name just as it is. If you already have a toy with that name, the code starts adding little numbers in parentheses, like one or two, to the end of the name until it finds one that is brand new.
After it finds a perfect name that nobody else is using, it writes that name down in a notebook. This notebook helps it remember which names are already taken. Whenever a new name comes along, the code checks the notebook again to make sure it stays unique. It continues doing this for every single name in your list until every toy has its own special label.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| FelixFan1122 | C# | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| FelixFan1122 | C# | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1914: Cyclically Rotating a Grid
- problem 1449: Form Largest Integer With Digits That Add up to Target
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality