Java Solution using 2 maps without final iteration


  • 0
    J

    The idea is to use 2nd map to track the index of the list appropriate to content. We add unique content to the 1st map with corresponding file, if map already contains content it means there are at least 2 files with the same content and we add it to the result.

    public List<List<String>> findDuplicate(String[] paths) {
    List<List<String>> lists = new ArrayList<>();

        Map<String, List<String>> map = new HashMap<>();
        Map<String, Integer> indexMap = new HashMap<>();
        
        int n = paths.length;
        
        for (int i = 0; i < n; i++) {
            String split[] = paths[i].split(" ");
            
            String dir = split[0];
            
            for (int j = 1; j < split.length; j++) {
                int index = split[j].indexOf("(");
                
                String fileName = dir + "/" + split[j].substring(0, index);
                String content = split[j].substring(index);
                
                List<String> list;
                
                if (map.containsKey(content)) {
                    if (indexMap.containsKey(content)) {
                        lists.get(indexMap.get(content)).add(fileName);
                    } else {
                        list = map.get(content);
                        list.add(fileName);
                        
                        lists.add(list);
                        
                        indexMap.put(content, lists.size() - 1);
                    }
                } else { 
                    list = new ArrayList<String>();
                    list.add(fileName);
                    
                    map.put(content, list);
                }  
            }
        }
        
        return lists;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.