File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
solution/1900-1999/1948.Delete Duplicate Folders in System Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import defaultdict
2
+
3
+ class TrieNode :
4
+ def __init__ (self ):
5
+ self .children = defaultdict (TrieNode )
6
+ self .id = None
7
+
8
+ class Solution :
9
+ def deleteDuplicateFolder (self , paths ):
10
+ # Step 1: Build a Trie (Tree) to represent the file system structure
11
+ root = TrieNode ()
12
+
13
+ for path in paths :
14
+ node = root
15
+ for folder in path :
16
+ node = node .children [folder ]
17
+
18
+ # Step 2: Assign unique IDs to the subtrees for easier comparison
19
+ subtree_map = defaultdict (list )
20
+ def get_id (node ):
21
+ if not node .children :
22
+ return 0 # Empty subtree
23
+ subtree_tuple = tuple ((name , get_id (child )) for name , child in sorted (node .children .items ()))
24
+ subtree_id = hash (subtree_tuple )
25
+ subtree_map [subtree_id ].append (node )
26
+ return subtree_id
27
+
28
+ get_id (root )
29
+
30
+ # Step 3: Mark duplicate subtrees by examining the subtree map
31
+ duplicates = set ()
32
+ for nodes in subtree_map .values ():
33
+ if len (nodes ) > 1 : # If more than one node has the same subtree ID, mark as duplicate
34
+ for node in nodes :
35
+ duplicates .add (node )
36
+
37
+ # Step 4: Reconstruct the remaining paths
38
+ ans = []
39
+
40
+ def collect_paths (node , path ):
41
+ if node in duplicates :
42
+ return # Skip this subtree because it's marked for deletion
43
+ if path :
44
+ ans .append (path [:])
45
+ for folder , child in sorted (node .children .items ()):
46
+ path .append (folder )
47
+ collect_paths (child , path )
48
+ path .pop ()
49
+
50
+ collect_paths (root , [])
51
+
52
+ return ans
You can’t perform that action at this time.
0 commit comments