Problem 1233

Abstract / Summary

Remove all subfolders from a list of folders to keep only the top level folders.

Note

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

Python 1233.py

class Solution:
    def removeSubfolders(self, folder: List[str]) -> List[str]:
        have = set()
        for f in sorted(folder):
            sub   = False       # subfolder
            parts = f.split("/")
            build = ""
            for p in parts[1:]: # skip the initial string, it's always empty
                build += "/" + p
                if build in have:
                    sub = True
                    break
            have.add(f)

            if not sub:
                yield f
16 lines | 524 bytes | submitted March 9, 2024 | GitHub   13% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Depth First Search
  • String
  • Trie
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.removeSubfolders method receives a list of folder paths and returns an iterator that yields only the top-level folders, discarding any path that is a subfolder of a previously encountered folder. The algorithm relies on lexical sorting of the input, incremental construction of each folder’s prefix, and a hash set for constant-time membership checks.

Key Steps

Sorting the Input List

The first operation arranges the folder strings in lexicographic order.

for f in sorted(folder):

Sorting guarantees that any parent directory appears before its children because the “/” separator sorts before alphabetic characters. This ordering is essential for the subsequent detection of subfolders.

Detecting Subfolders

For each folder f, the code splits the path on the slash character, then iteratively rebuilds each prefix starting after the leading empty component.

parts = f.split("/")
build = ""
for p in parts[1:]:          # skip the initial empty string
    build += "/" + p
    if build in have:
        sub = True
        break

During the loop, build represents the current prefix (e.g., /a, /a/b). If any prefix already exists in the have set, the current folder is identified as a subfolder (sub = True) and the inner loop terminates early.

Storing and Yielding Results

After the subfolder check, the original folder path is added to the set of known folders, and the folder is yielded only when it was not marked as a subfolder.

have.add(f)
if not sub:
    yield f

Adding the folder to have before the next iteration ensures that later paths can be compared against it.

Edge Cases Handled

The implementation gracefully handles several special situations. When the input contains the root folder represented as "/" the split operation yields ['', '']; the inner loop processes the single empty component, builds "/" and correctly records it in the set, preventing any deeper paths from being emitted. Duplicate folder strings are also managed: the first occurrence is added to have and yielded, while subsequent identical entries are recognized as subfolders because the exact prefix already exists, causing them to be omitted from the output. Extremely deep nesting is supported because the algorithm builds prefixes incrementally rather than relying on recursion, avoiding stack overflow concerns.

Performance Optimizations

The algorithm leverages a hash set (have) to achieve constant-time checks for previously seen prefixes, eliminating the need for linear scans of the result list. By sorting the input once, the method ensures that each parent folder is processed before any of its children, allowing the early-break condition to stop the inner loop as soon as a matching prefix is found. The incremental construction of build avoids repeated string concatenations of the full path; each iteration appends only a single component, keeping the per-folder work proportional to its depth rather than its total length. These choices collectively reduce the overall work to a single pass over the sorted list with minimal overhead per element.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a giant collection of folder names written on paper. Some folders are tucked away inside other folders, like a little box inside a bigger box. This code plays a game where it goes through all the folders to find the ones that are not hidden inside another one.

First, the code lines up all the folder names in alphabetical order, just like organizing books on a shelf. It creates an empty space called have to keep track of the main folders found so far.

The code looks at each folder one by one. It slices the folder name into little pieces, splitting them wherever there is a slash. Then, it starts building the path again, piece by piece, from the front. As it builds, it checks whether that path is already in the have space. If it finds a match, that means a parent folder already exists, so it labels the current folder as a subfolder and stops looking.

After checking, if the folder is still not marked as a subfolder, it gets added to the have space so the computer remembers it. Then, the computer announces the name of this main folder for everyone to see.

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.74 | σ = 1.35

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
23 links | 11 authors | 7 languages

Videos

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

Solved On The Same Day

2 solutions   March 9, 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