AlgoInsight

DSA problem

Remove Sub-Folders from the Filesystem

MediumTriesPattern: Triestop600AmazonGoogleMicrosoftAppleBloomberg

Given a list of folder paths folder, remove all sub-folders in those paths and return the folders in any order. A folder b is a sub-folder of folder a if and only if a is a prefix of b AND that prefix is followed by a / in b. For example, /a/b is a sub-folder of /a, but /a/b is NOT a sub-folder of /a/b/c even though /a/b is a prefix of /a/b/c (the relationship is reversed there).

The trailing-slash requirement matters: /abc is not a sub-folder of /ab because the prefix /ab is followed by c instead of /. A correct algorithm must respect this boundary explicitly.

The most elegant solution sorts the folders lexicographically. After sorting, any sub-folder is guaranteed to appear immediately after its parent (since the parent string is a prefix of the sub-folder string), so a single pass can keep only the top-level folders. Maintain a list of accepted folders; for each candidate, accept it unless it begins with lastAccepted + '/'.

This runs in O(N log N * L) time for sorting where N is the number of folders and L is the average length, plus O(N * L) for the linear scan. Space is O(N * L) for the result. An alternative trie approach builds a tree of path segments and accepts a folder only at the first node it reaches with an isEnd flag along its path; that yields the same asymptotic behavior but with higher constants and more memory.

Examples

Example 1
Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: /a/b is inside /a; /c/d/e is inside /c/d. /c/f is its own folder because /c/f is not under any kept folder (note /c is NOT in the input).
Example 2
Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Both /a/b/c and /a/b/d are inside /a, so the only top-level folder is /a.
Example 3
Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]
Explanation: /a/b/ca is NOT a sub-folder of /a/b/c because the prefix /a/b/c is followed by "a", not "/". So all three folders survive.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

triearraystringdepth-first-searchsorting

Browse all DSA problems