forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f96675d
commit 18c0a9e
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
solution/1900-1999/1948.Delete Duplicate Folders in System/Solution.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
from collections import defaultdict | ||
|
||
class TrieNode: | ||
def __init__(self): | ||
self.children = defaultdict(TrieNode) | ||
self.id = None | ||
|
||
class Solution: | ||
def deleteDuplicateFolder(self, paths): | ||
# Step 1: Build a Trie (Tree) to represent the file system structure | ||
root = TrieNode() | ||
|
||
for path in paths: | ||
node = root | ||
for folder in path: | ||
node = node.children[folder] | ||
|
||
# Step 2: Assign unique IDs to the subtrees for easier comparison | ||
subtree_map = defaultdict(list) | ||
def get_id(node): | ||
if not node.children: | ||
return 0 # Empty subtree | ||
subtree_tuple = tuple((name, get_id(child)) for name, child in sorted(node.children.items())) | ||
subtree_id = hash(subtree_tuple) | ||
subtree_map[subtree_id].append(node) | ||
return subtree_id | ||
|
||
get_id(root) | ||
|
||
# Step 3: Mark duplicate subtrees by examining the subtree map | ||
duplicates = set() | ||
for nodes in subtree_map.values(): | ||
if len(nodes) > 1: # If more than one node has the same subtree ID, mark as duplicate | ||
for node in nodes: | ||
duplicates.add(node) | ||
|
||
# Step 4: Reconstruct the remaining paths | ||
ans = [] | ||
|
||
def collect_paths(node, path): | ||
if node in duplicates: | ||
return # Skip this subtree because it's marked for deletion | ||
if path: | ||
ans.append(path[:]) | ||
for folder, child in sorted(node.children.items()): | ||
path.append(folder) | ||
collect_paths(child, path) | ||
path.pop() | ||
|
||
collect_paths(root, []) | ||
|
||
return ans |