
Sponsored
Sponsored
To find duplicate files by their content, we can use a HashMap (or Dictionary). For each directory info string, parse the directory path and the files with their contents. Use the content as the key in the map and store full path of the file as its value. After parsing all inputs, the map keys with more than one value represent duplicate files.
Time Complexity: O(n), where n is the total number of characters in all file paths. We iterate over each character once.
Space Complexity: O(n) to store the lists of file paths in the dictionary.
1import java.util.*;
2
3public class DuplicateFiles {
4 public List<List<String>> findDuplicate(String[] paths) {
5 Map<String, List<String>> contentMap = new HashMap<>();
6 for (String path : paths) {
7 String[] parts = path.split(" ");
8 String root = parts[0];
9 for (int i = 1; i < parts.length; i++) {
10 String[] nameContent = parts[i].split("\\(");
11 String name = nameContent[0];
12 String content = nameContent[1].substring(0, nameContent[1].length() - 1);
13 contentMap.computeIfAbsent(content, k -> new ArrayList<>()).add(root + "/" + name);
14 }
15 }
16 List<List<String>> result = new ArrayList<>();
17 for (List<String> group : contentMap.values()) {
18 if (group.size() > 1) {
19 result.add(group);
20 }
21 }
22 return result;
23 }
24}In Java, we use a HashMap to collect file paths by their content. Using the split method, we separate the root directory from the files. In a loop, the file name and contents are isolated, enabling us to map the full path of each file under its content as a key. Finally, groups with more than one entry are added to the result list and returned.
This approach is based on directly processing string data and arranging results using a 2D array. Strings are manipulated to extract directory data, file names, and contents into standalone variables, then append paths to a growing structure. Compared to hash maps, this method uses arrays to aggregate identical files.
Time Complexity: O(n), where n is the total input character count due to one-pass evaluation.
Space Complexity: O(n), maintaining paths and intermediate arrays.
1import java.util
The Java solution also opts for hand-coded parsing over utility function exploitation. By fixing delimiters around file names and content parentheses, the program extracts needed identifiers and groups paths expediently through manual index use.