Remove Sub-Folders from the Filesystem in Python

Problem Description

Ah, the classic dilemma of digital organization! Imagine your computer’s file system is like your closet. You know, the one where you shove all your clothes into one corner, and then you have to dig through a mountain of sweaters to find that one elusive shirt? Well, the “Remove Sub-Folders from the Filesystem” problem is here to save you from that chaos!

In this problem, you’re given a list of folder paths, and your mission, should you choose to accept it, is to eliminate any subfolders that are nested within other folders. Think of it as decluttering your closet by tossing out those pesky nested boxes that only serve to confuse you.

For example, if you have folders like:

  • /a
  • /a/b
  • /c/d
  • /c/d/e

You only want to keep the top-level folders, which means /a and /c are your winners! The subfolders /a/b and /c/d/e are outta here!

Code Solution


class Solution:
    def removeSubfolders(self, folder: list[str]) -> list[str]:
        ans = []
        prev = ""

        folder.sort()

        for f in folder:
            if len(prev) > 0 and f.startswith(prev) and f[len(prev)] == '/':
                continue
            ans.append(f)
            prev = f

        return ans

Approach

The approach here is as straightforward as a Sunday morning! First, we sort the list of folders. This way, any subfolder will always come right after its parent folder. Then, we loop through the sorted list and check if the current folder starts with the previous folder’s name followed by a /. If it does, we skip it because it’s a subfolder. If not, we add it to our answer list. Simple, right?

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n log n) due to the sorting step, where n is the number of folders.
Space Complexity O(n) for storing the result in the answer list.

Real-World Example

Imagine you’re organizing a family reunion. You have a main folder for the event, and then you create subfolders for each family member. But wait! Your cousin decided to create a subfolder for their kids, and then their kids created subfolders for their toys. Before you know it, you have a digital mess! This problem helps you streamline that chaos by keeping only the main folders, just like you would do in real life when you decide to keep only the essentials and toss the clutter.

Similar Problems

If you enjoyed this problem, you might also like these: