Ctrl K

Purge Twin Folders

Hard
A sync glitch has filled a file system with copied folders. You get a list folders; each item is the path to a folder as a list of names, so ["home", "me", "notes"] stands for /home/me/notes. Two folders (at any depth, not necessarily the same level) are **twins** if their contents are non-empty and laid out identically: the same subfolder names, with identical structure inside those, all the way down. The names of the twin folders themselves do not matter. Every folder that has at least one twin is marked and then deleted together with everything inside it. Deletion happens once: if some folders become identical after it, they are left alone. Return the paths of all remaining folders in any order.
Example 1
folders=[["img"], ["img", "raw"], ["music"], ["music", "raw"], ["docs"]] → [['docs']]

/img and /music each hold a single empty folder raw, so their contents match and both go, along with their raw. /docs is empty, and empty folders never count as twins, so it stays.

Example 2
folders=[["a"], ["a", "x"], ["a", "x", "z"], ["b"], ["b", "y"], ["b", "y", "z"], ["b", "w"]] → [['a'], ['b', 'w'], ['b']]

/a/x and /b/y both contain just an empty z, so they are twins and get removed. Afterwards /a is empty and /b still holds w, but there is no second pass. What remains is /a, /b and /b/w.

Constraints
  • 1 ≤ len(folders) ≤ 2·10⁴
  • 1 ≤ len(folders[i]) ≤ 500
  • 1 ≤ name length ≤ 10, names use lowercase English letters and digits
  • Total length of all names ≤ 2·10⁵
  • No path appears twice
  • Every non-root folder's parent is also in the list
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardGlued Into a Palindrome HardWords That Fit Each Puzzle HardFraming Word Pairs HardPalindromic Subtrees Hard
loading Python…
Input
folders=[["img"], ["img", "raw"], ["music"], ["music", "raw"], ["docs"]]
Expected
[['docs']]

Run checks the first 3 tests in your browser. Submit checks all 42 tests on the server, hidden ones included.