|
| 1 | +/** |
| 2 | + * Title: Delete Duplicate Folders in System |
| 3 | + * Description: Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 06/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {string[][]} paths |
| 10 | + * @return {string[][]} |
| 11 | + */ |
| 12 | +class Node { |
| 13 | + constructor(val, parent) { |
| 14 | + (this.val = val), (this.parent = parent), (this.children = {}), this.hash; |
| 15 | + } |
| 16 | +} |
| 17 | +class Trie { |
| 18 | + constructor() { |
| 19 | + this.root = new Node(""); |
| 20 | + this.hashMemo = {}; |
| 21 | + } |
| 22 | + insert(path) { |
| 23 | + let cur = this.root; |
| 24 | + for (let node of path) |
| 25 | + if (cur.children[node] !== undefined) cur = cur.children[node]; |
| 26 | + else |
| 27 | + (cur.children[node] = new Node(node, cur)), (cur = cur.children[node]); |
| 28 | + } |
| 29 | + traverse(node = this.root) { |
| 30 | + node.hash = []; |
| 31 | + if (node.children) |
| 32 | + for (let child of Object.values(node.children)) |
| 33 | + node.hash.push(this.traverse(child)); |
| 34 | + node.hash = node.hash.join("~"); |
| 35 | + if (node.hash !== "") { |
| 36 | + if (this.hashMemo[node.hash] === undefined) this.hashMemo[node.hash] = []; |
| 37 | + this.hashMemo[node.hash].push(node); |
| 38 | + return node.val + "/[" + node.hash + "]"; |
| 39 | + } |
| 40 | + return node.val; |
| 41 | + } |
| 42 | + delete(node = this.root) { |
| 43 | + if (!node || node.hash === undefined) return; |
| 44 | + else if (this.hashMemo[node.hash] && this.hashMemo[node.hash].length > 1) |
| 45 | + for (let todelete of this.hashMemo[node.hash]) |
| 46 | + delete todelete.parent.children[todelete.val]; |
| 47 | + else for (let child of Object.values(node.children)) this.delete(child); |
| 48 | + } |
| 49 | + serialize(node = this.root, stack = [], res = []) { |
| 50 | + if (node.val !== "") stack.push(node.val), res.push([...stack]); |
| 51 | + for (let child of Object.values(node.children)) |
| 52 | + this.serialize(child, stack, res); |
| 53 | + stack.pop(); |
| 54 | + return res; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +var deleteDuplicateFolder = function (paths) { |
| 59 | + let T = new Trie(); |
| 60 | + for (let P of paths) T.insert(P); |
| 61 | + T.traverse(); |
| 62 | + T.delete(); |
| 63 | + return T.serialize(); |
| 64 | +}; |
0 commit comments