DEV Community

Cover image for 〽️ Beginner-Friendly Guide: "Remove Sub-Folders from Filesystem" – LeetCode 1233 (C++ | Python | JavaScript)
Om Shree
Om Shree

Posted on

〽️ Beginner-Friendly Guide: "Remove Sub-Folders from Filesystem" – LeetCode 1233 (C++ | Python | JavaScript)

Managing filesystem hierarchies is a fundamental operation across systems. In this problem, we are given a list of folder paths and need to remove sub-folders, retaining only the top-level directories. This challenge not only helps in understanding path manipulation but also teaches efficient sorting and string matching techniques.


🧠 Problem Summary

  • Input: A list of folder paths represented as strings, where each folder starts with '/' followed by lowercase letters.
  • Goal: Remove any folder that is a sub-folder of another.
  • Constraint: A sub-folder is defined if its path starts with another folder's path, immediately followed by a '/'.

Example:

  • Input: ["/a","/a/b","/c/d","/c/d/e","/c/f"]
  • Output: ["/a","/c/d","/c/f"]

File System

💡 Intuition

  1. Sorting: By sorting all folder paths lexicographically, parent folders naturally appear before their sub-folders.
  2. Tracking: Keep track of the previous folder added to the answer.
  3. Checking Sub-folder: For each folder, check if it starts with the prev folder plus '/'. If so, it's a sub-folder and should be skipped.
  4. Otherwise: Add the current folder to the answer and update prev.

🛠️ C++ Code

#include <vector>
#include <string>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<string> removeSubfolders(vector<string>& folder) {
        vector<string> ans;
        string prev;

        sort(folder.begin(), folder.end());

        for (const string& f : folder) {
            if (!prev.empty() && f.find(prev) == 0 && f[prev.length()] == '/')
                continue;
            ans.push_back(f);
            prev = f;
        }

        return ans;
    }
};
Enter fullscreen mode Exit fullscreen mode

🐍 Python Code

from typing import List

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

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

        return ans
Enter fullscreen mode Exit fullscreen mode

💻 JavaScript Code

var removeSubfolders = function(folder) {
    folder.sort();
    const ans = [];
    let prev = "";

    for (const f of folder) {
        if (prev && f.startsWith(prev) && f[prev.length] === '/') {
            continue;
        }
        ans.push(f);
        prev = f;
    }

    return ans;
};
Enter fullscreen mode Exit fullscreen mode

📝 Key Takeaways

  • Sorting: Sorting lexicographically is the core trick that ensures parent directories appear before sub-folders.
  • Prefix Check: f.find(prev) == 0 and f[prev.length()] == '/' efficiently checks for the sub-folder condition.
  • Performance: This approach is efficient, running in O(n log n) time due to sorting, where n is the number of folders.

✅ Final Thoughts

This problem is a great example of how simple sorting combined with careful prefix checking can solve seemingly complex hierarchical challenges. The technique is broadly useful in handling path-based or string-prefix problems across applications.

Top comments (4)

Collapse
 
sjxsubham profile image
SjxSubham

Solved 1 years ago... Thanks for remembering again

Collapse
 
om_shree_0709 profile image
Om Shree

Thanks Subham, Glad you liked it!

Collapse
 
thedeepseeker profile image
Anna kowoski

Good Work!!!

Collapse
 
om_shree_0709 profile image
Om Shree

Thanks Anna.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.