← All problems

1233. Remove Sub Folders from the Filesystem

MediumOpen on LeetCodeProblem statement

Problem Statement

1233. Remove Sub-Folders from the Filesystem

Medium


Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.

If a folder[i] is located within another folder[j], it is called a sub-folder of it. A sub-folder of folder[j] must start with folder[j], followed by a "/". For example, "/a/b" is a sub-folder of "/a", but "/b" is not a sub-folder of "/a/b/c".

The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.

 

Example 1:

Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.

Example 2:

Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".

Example 3:

Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]

 

Constraints:

Java — 2pass trie

Source file
class Solution {
    private class TrieNode {
        Map<String, TrieNode> children = new HashMap<>();
        boolean isVisited = false;
    }

    private class Trie {
        TrieNode root;

        Trie() {
            root = new TrieNode();
        }

        void insert(String folder) {
            String[] path = folder.split("/");
            TrieNode curr = root;
            for (String dir : path) {
                curr.children.putIfAbsent(dir, new TrieNode());
                curr = curr.children.get(dir);
                if(curr.isVisited)  // skip traversing a nested path of already seen dir
                    return;
            }
            curr.children.clear();  // clear subfolders encountered previously
            curr.isVisited = true;
        }

        boolean contains(String folder) {
            String[] path = folder.split("/");
            TrieNode curr = root;
            for (String dir : path) {
                if(!curr.children.containsKey(dir))
                    return false;
                curr = curr.children.get(dir);
            }
            return curr.isVisited;
        }
    }

    public List<String> removeSubfolders(String[] folder) {
        Trie trie = new Trie();
        for (String f : folder)
            trie.insert(f);
        List<String> prunedFolderList = new ArrayList<>();
        for(String f: folder)
            if(trie.contains(f))
                prunedFolderList.add(f);
        return prunedFolderList;
    }
}