Find Duplicate File in System (LeetCode 609): Solution and Explanation
Each input string names a directory and the files in it with their contents in parentheses. Return every group of two or more full paths whose files have identical content. Groups and paths may come in any order.
Intuition
Two files are duplicates exactly when their contents match, no matter what they are called or where they live. That makes the content string the key to group by.
The only real work is parsing. The first space-separated token of an entry is the directory, and each remaining token is name(content). Cutting at the first '(' gives the name, and the text up to the last ')' is the content.
Feed every file into a map from content to a list of directory/name paths. At the end, any list with at least two paths is a duplicate group.
Approach: Parse and group by content
- Create an empty map from content to a list of paths.
- For each entry, split it on spaces. Call the first token
root. - For each remaining token, find the index of '('. The name is before it, the content is between it and the final ')'.
- Append
root + '/' + nameto the list for that content. - Return every list whose length is at least 2.
Step-by-step example
paths = ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"]
- Entry 0, directory
root/a:1.txtwith abcd starts bucket abcd,2.txtwith efgh starts bucket efgh. - Entry 1, directory
root/c:3.txtwith abcd joins bucket abcd, which now has 2 paths. - Entry 2, directory
root/c/d:4.txtwith efgh joins bucket efgh. - Entry 3, directory
root:4.txtwith efgh joins bucket efgh, now 3 paths. - Both buckets have at least two paths:
[["root/a/1.txt","root/c/3.txt"],["root/a/2.txt","root/c/d/4.txt","root/4.txt"]].
Code: Python, Java, C++
1class Solution:
2 def findDuplicate(self, paths: List[str]) -> List[List[str]]:
3 groups = {}
4 for entry in paths:
5 parts = entry.split(' ')
6 root = parts[0]
7 for f in parts[1:]:
8 k = f.index('(')
9 name, content = f[:k], f[k + 1:-1]
10 groups.setdefault(content, []).append(root + '/' + name)
11 return [g for g in groups.values() if len(g) > 1]1class Solution {
2 public List<List<String>> findDuplicate(String[] paths) {
3 Map<String, List<String>> groups = new LinkedHashMap<>();
4 for (String entry : paths) {
5 String[] parts = entry.split(" ");
6 String root = parts[0];
7 for (int p = 1; p < parts.length; p++) {
8 int k = parts[p].indexOf('(');
9 String name = parts[p].substring(0, k);
10 String content = parts[p].substring(k + 1, parts[p].length() - 1);
11 groups.computeIfAbsent(content, x -> new ArrayList<>()).add(root + "/" + name);
12 }
13 }
14 List<List<String>> res = new ArrayList<>();
15 for (List<String> g : groups.values()) if (g.size() > 1) res.add(g);
16 return res;
17 }
18}1class Solution {
2public:
3 vector<vector<string>> findDuplicate(vector<string>& paths) {
4 unordered_map<string, vector<string>> groups;
5 vector<string> order;
6 for (const string& entry : paths) {
7 stringstream ss(entry);
8 string root, f;
9 ss >> root;
10 while (ss >> f) {
11 size_t k = f.find('(');
12 string name = f.substr(0, k);
13 string content = f.substr(k + 1, f.size() - k - 2);
14 if (!groups.count(content)) order.push_back(content);
15 groups[content].push_back(root + "/" + name);
16 }
17 }
18 vector<vector<string>> res;
19 for (const string& c : order) if (groups[c].size() > 1) res.push_back(groups[c]);
20 return res;
21 }
22};Time and space complexity
O(L)
Every character of the input is scanned a constant number of times while splitting and hashing, where L is the total input length.
O(L)
The map stores each content string once and every full path once.
Other approaches
Group by size and hash first (time O(L), space O(number of files))
For a real file system, group files by size, then by a hash of their content, and compare bytes only inside a group. It avoids reading or storing whole files when most sizes differ.
Sort all (content, path) pairs (time O(L log n), space O(L))
Collect pairs, sort by content, and cut runs of equal content. Simple, but sorting adds a log factor.
Common mistakes
- Including groups of size one. Only contents shared by at least two files form a group.
- Splitting the file token on ')' as well as '(' and losing part of the name, or keeping the trailing ')' in the content.
- Joining directory and name without the '/' separator.
- Comparing file names instead of contents. Files with the same name in different folders are not duplicates unless their contents match.
Frequently asked questions
Does the order of the output matter?
No. Both the order of the groups and the order of the paths inside a group are free, and the checker accepts any order.
What if the files were huge in a real system?
Do not load whole files into a map. Group by file size first, then by a hash of chunks, and confirm equality byte by byte only within a candidate group.
Why is the content a safe map key?
Two files are duplicates exactly when their content strings are equal, and a hash map compares keys by value, so equal contents land in the same bucket.