MediumNo. 0609

Find Duplicate File in System — LeetCode 609 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
2 min

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0599Minimum Index Sum of Two ListsEasy
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.