#1233

Remove Sub-Folders from the Filesystem

Medium
ArrayStringDepth-First SearchTrieSortingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the folders first, we can efficiently check for sub-folders in a single pass. This way, we only need to compare each folder with the last added folder in the result.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the folder list lexicographically.
  2. 2Step 2: Initialize an empty list to store the result.
  3. 3Step 3: Iterate through the sorted list and add a folder to the result if it does not start with the last added folder followed by a '/'.
solution.py7 lines
1def removeSubfolders(folder):
2    folder.sort()
3    result = []
4    for f in folder:
5        if not result or not f.startswith(result[-1] + '/'): 
6            result.append(f)
7    return result

Complexity note: The sorting step is O(n log n), and we traverse the sorted list once, leading to a linear pass afterward.

  • 1Sorting the folders helps in efficiently identifying sub-folders.
  • 2Using a single pass after sorting reduces the time complexity significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.