Approach
Sorting and greedy selection
For Delete Duplicate Folders in System, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 45 lines of Python from the credited upstream file 1948.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode:2 def __init__(self):3 self.children: dict[str, TrieNode] = {}4 self.deleted = False5 6 7class Solution:8 def deleteDuplicateFolder(self, paths: list[list[str]]) -> list[list[str]]:9 ans = []10 root = TrieNode()11 subtreeToNodes: dict[str, list[TrieNode]] = collections.defaultdict(list)12 13 14 for path in sorted(paths):15 node = root16 for s in path:17 node = node.children.setdefault(s, TrieNode())18 19 20 def buildSubtreeToRoots(node: TrieNode) -> str:21 subtree = '(' + ''.join(s + buildSubtreeToRoots(node.children[s])22 for s in node.children) + ')'23 if subtree != '()':24 subtreeToNodes[subtree].append(node)25 return subtree26 27 buildSubtreeToRoots(root)28 29 30 for nodes in subtreeToNodes.values():31 if len(nodes) > 1:32 for node in nodes:33 node.deleted = True34 35 36 def constructPath(node: TrieNode, path: list[str]) -> None:37 for s, child in node.children.items():38 if not child.deleted:39 constructPath(child, path + [s])40 if path:41 ans.append(path)42 43 constructPath(root, [])44 return ans45