A bug left many duplicate folders in a file system. You are given a 2D list paths, where paths[i] is the absolute path of the i-th folder written as a list of folder names. For example, ["one", "two", "three"] is the path /one/two/three.
Two folders are identical when they contain the same non-empty set of subfolders with the same underlying subfolder structure. The folders do not need to be at the root level or at the same depth to be identical. When two or more folders are identical, mark each of them and all of their subfolders. For example, if /a and /b are identical, then /a/x, /a/x/y, /b/x and /b/x/y are marked as well, because every folder under a marked folder is marked whether or not it is identical to another folder on its own.
Once every identical folder and its subfolders are marked, the file system deletes all marked folders. It runs the deletion only once, so folders that become identical after the deletion are kept.
Return the paths of the folders that remain.
Function Signature
def delete_duplicate_folder(paths: list[list[str]]) -> list[list[str]]:
Rules
-
Two folders are identical when each has at least one subfolder, both have the same set of subfolder names, and the subfolders with matching names are identical in structure all the way down. An empty subfolder matches only an empty subfolder.
-
Empty folders are never identical to each other. They are deleted only when an ancestor is marked.
-
A folder's own name plays no part in the comparison. Only what is inside it counts.
-
Return the remaining paths sorted in ascending lexicographic order: compare two paths name by name, and when one path is a prefix of the other, the shorter path comes first. Return an empty list if every folder is deleted.
Constraints
-
1 <= len(paths) <= 2 * 10^4
-
1 <= len(paths[i]) <= 500
-
1 <= len(paths[i][j]) <= 10
-
1 <= sum(len(paths[i][j])) <= 2 * 10^5
-
paths[i][j]
consists of lowercase English letters.
-
No two paths lead to the same folder.
-
For any folder not at the root level, its parent folder is also in the input.
Examples
Example 1
Input: paths = [["a"], ["c"], ["d"], ["a", "b"], ["c", "b"], ["d", "a"]]
Output: [["d"], ["d", "a"]]
/a and /c each contain only the empty folder b, so they are identical and are deleted together with their b. /d contains a instead of b, so /d and /d/a remain.
Example 2
Input: paths = [["a"], ["c"], ["a", "b"], ["c", "b"], ["a", "b", "x"], ["a", "b", "x", "y"], ["w"], ["w", "y"]]
Output: [["a"], ["a", "b"], ["c"], ["c", "b"]]
/a/b/x and /w each contain only the empty folder y, so both are deleted along with their y. /a and /c are not identical, because /a/b contains x while /c/b is empty.
Example 3
Input: paths = [["m"], ["m", "k"], ["m", "k", "y"], ["m", "z"], ["n"], ["n", "j"], ["n", "j", "y"], ["n", "z"]]
Output: [["m"], ["m", "z"], ["n"], ["n", "z"]]
/m/k and /n/j each hold only an empty y, so they are deleted. Afterward /m and /n both hold only z, but the deletion runs once, so both stay.