Skip to main content
Back to problems
Leetcode
Medium
Sorting
Strings
Arrays
Remove Sub Folders From The Filesystem

Given a list of folder paths, return only the top-level folders after removing any path that is a subfolder of another path.

Acceptance 100%
Problem Statement

Problem

You are given an array of folder paths. A folder path may contain nested subfolders, written using / as the separator.

Your task is to remove every folder that is contained inside another folder from the same list. A folder a/b is considered a subfolder of a if the path starts with a/ and has a as an exact folder prefix.

Return the remaining folders in any valid order, with all subfolders removed.

Notes

  • A folder is only a subfolder if the prefix ends at a folder boundary.
  • For example, /a/b is a subfolder of /a, but /ab is not a subfolder of /a.
  • The input may contain multiple folders at different depths.

Goal

Keep only the highest folder from each nested chain.

Input Format

  • An array of strings folder where each string is a folder path.
  • Each path uses / to separate folder names.

Output Format

  • Return an array of strings containing only the folders that are not subfolders of any other folder in the input.

Constraints

  • 1 <= folder.length
  • Folder paths are non-empty strings.
  • Folder names contain only lowercase letters.
  • Paths use / as separator.
  • The answer may be returned in any order unless otherwise specified by the platform.
Examples
Sample cases returned by the problem API.

Example 1

Input

["/a","/a/b","/c/d","/c/d/e","/c/f"]

Output

["/a","/c/d","/c/f"]

Explanation

/a/b is inside /a, and /c/d/e is inside /c/d. The remaining folders are the top-level ones among the given paths.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.