July 23, 2022

609. Find Duplicate File in System

609. Find Duplicate File in System

Use Hash Map.

For follow up questions: Refer to this post.

class Solution {
    public List<List<String>> findDuplicate(String[] paths) {
        Map<String, List<String>> map = new HashMap<>();
        List<List<String>> res = new ArrayList<>();
        for (String path : paths) {
            String[] parts = path.split(" ");
            String filePath = parts[0];
            for (int i = 1; i < parts.length; i++) {
                int start = parts[i].lastIndexOf("(");
                int end = parts[i].lastIndexOf(")");
                String content = parts[i].substring(start, end + 1);                    
                filePath = filePath + "/" + parts[i].substring(0, start);
                if (map.containsKey(content)) {
                    map.get(content).add(filePath);
                } else {
                    List<String> filePaths = new ArrayList<>();
                    filePaths.add(filePath);
                    map.put(content, filePaths);
                }
                filePath = parts[0];
            }
        }
        
        for (String key : map.keySet()) {
            List<String> value = map.get(key);
            if (value.size() > 1) {
                res.add(value);
            }
        }
        return res;
    }
}
comments powered by Disqus