Problem 1487

Abstract / Summary

Given a list of file names, change duplicates by adding the smallest possible number to the end in parentheses until all names are unique.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
16 lines | 539 bytes | submitted April 8, 2024 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 39% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 at 0 and 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 names list 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 from 0 after 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.00 | σ = 1.68

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
26 links | 15 authors | 7 languages

Videos

1 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 solutions   April 8, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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