#1948
Delete Duplicate Folders in System
HardArrayHash TableStringTrieHash FunctionHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution utilizes a hash map to store folder structures and their paths, allowing for efficient identification of duplicates. By representing the folder structures as strings, we can quickly compare them.
⚙️
Algorithm
4 steps- 1Step 1: Create a hash map to store folder structures and their paths.
- 2Step 2: For each path, generate a unique representation of its structure.
- 3Step 3: If a structure is already in the map, mark it as a duplicate.
- 4Step 4: Filter out the marked duplicates and return the remaining paths.
solution.py18 lines
1def deleteDuplicateFolders(paths):
2 from collections import defaultdict
3
4 def get_structure(path):
5 return '/'.join(sorted(path))
6
7 structures = defaultdict(list)
8 duplicates = set()
9
10 for path in paths:
11 structure = get_structure(path)
12 structures[structure].append(path)
13
14 for key, value in structures.items():
15 if len(value) > 1:
16 duplicates.add(key)
17
18 return [path for path in paths if get_structure(path) not in duplicates]ℹ
Complexity note: The time complexity is O(n) because we only traverse the list of paths a few times. The space complexity is O(n) due to the storage of folder structures and duplicates.
- 1Identical folders are determined by their subfolder structures.
- 2Using a hash map allows for efficient storage and retrieval of folder structures.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.