Find Duplicate File in System — LeetCode 609 Python Solution
- Problem
- #609
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
Example
- Input
- paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
- Output
- [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Python solution
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
d = defaultdict(list)
for p in paths:
ps = p.split()
for f in ps[1:]:
i = f.find('(')
name, content = f[:i], f[i + 1 : -1]
d[content].append(ps[0] + '/' + name)
return [v for v in d.values() if len(v) > 1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 609. Find Duplicate File in System is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 609. Find Duplicate File in System?
- LeetCode 609. Find Duplicate File in System is rated Medium on LeetCode.
- What is the time complexity of LeetCode 609. Find Duplicate File in System?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 609. Find Duplicate File in System?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 609. Find Duplicate File in System cover?
- LeetCode 609. Find Duplicate File in System is tagged Array, Hash Table and String on LeetCode.