609. Find Duplicate File in System LeetCode Solution

In this guide, you will get 609. Find Duplicate File in System LeetCode Solution with the best time and space complexity. The solution to Find Duplicate File in System problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find Duplicate File in System solution in C++
  4. Find Duplicate File in System solution in Java
  5. Find Duplicate File in System solution in Python
  6. Additional Resources
609. Find Duplicate File in System LeetCode Solution image

Problem Statement of Find Duplicate File in System

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.
A group of duplicate files consists of at least two files that have the same content.
A single directory info string in the input list has the following format:

“root/d1/d2/…/dm f1.txt(f1_content) f2.txt(f2_content) … fn.txt(fn_content)”

It means there are n files (f1.txt, f2.txt … fn.txt) with content (f1_content, f2_content … fn_content) respectively in the directory “root/d1/d2/…/dm”. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

“directory_path/file_name.txt”

Example 1:
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”]]
Example 2:
Input: paths = [“root/a 1.txt(abcd) 2.txt(efgh)”,”root/c 3.txt(abcd)”,”root/c/d 4.txt(efgh)”]
Output: [[“root/a/2.txt”,”root/c/d/4.txt”],[“root/a/1.txt”,”root/c/3.txt”]]

Constraints:

1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 3000
1 <= sum(paths[i].length) <= 5 * 105
paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
You may assume no files or directories share the same name in the same directory.
You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.

Follow up:

Imagine you are given a real file system, how will you search files? DFS or BFS?
If the file content is very large (GB level), how will you modify your solution?
If you can only read the file by 1kb each time, how will you modify your solution?
What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
How to make sure the duplicated files you find are not false positive?

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

609. Find Duplicate File in System LeetCode Solution in C++

class Solution {
 public:
  vector<vector<string>> findDuplicate(vector<string>& paths) {
    vector<vector<string>> ans;
    unordered_map<string, vector<string>> contentToFilePaths;

    for (const string& path : paths) {
      istringstream iss(path);
      string rootPath;
      iss >> rootPath;  // "root/d1/d2/.../dm"

      string fileAndContent;
      while (iss >> fileAndContent) {  // "fn.txt(fn_content)"
        const int l = fileAndContent.find('(');
        const int r = fileAndContent.find(')');
        // "fn.txt"
        const string file = fileAndContent.substr(0, l);
        // "fn_content"
        const string content = fileAndContent.substr(l + 1, r - l - 1);
        // "root/d1/d2/.../dm/fn.txt"
        const string filePath = rootPath + '/' + file;
        contentToFilePaths[content].push_back(filePath);
      }
    }

    for (const auto& [_, filePaths] : contentToFilePaths)
      if (filePaths.size() > 1)
        ans.push_back(filePaths);

    return ans;
  }
};
/* code provided by PROGIEZ */

609. Find Duplicate File in System LeetCode Solution in Java

class Solution {
  public List<List<String>> findDuplicate(String[] paths) {
    List<List<String>> ans = new ArrayList<>();
    Map<String, List<String>> contentToFilePaths = new HashMap<>();

    for (final String path : paths) {
      final String[] words = path.split(" ");
      final String rootPath = words[0]; // "root/d1/d2/.../dm"
      for (int i = 1; i < words.length; ++i) {
        final String fileAndContent = words[i]; // "fn.txt(fn_content)"
        final int l = fileAndContent.indexOf('(');
        final int r = fileAndContent.indexOf(')');
        // "fn.txt"
        final String file = fileAndContent.substring(0, l);
        // "fn_content"
        final String content = fileAndContent.substring(l + 1, r);
        // "root/d1/d2/.../dm/fn.txt"
        final String filePath = rootPath + '/' + file;
        contentToFilePaths.putIfAbsent(content, new ArrayList<>());
        contentToFilePaths.get(content).add(filePath);
      }
    }

    for (List<String> filePaths : contentToFilePaths.values())
      if (filePaths.size() > 1)
        ans.add(filePaths);

    return ans;
  }
}
// code provided by PROGIEZ

609. Find Duplicate File in System LeetCode Solution in Python

class Solution:
  def findDuplicate(self, paths: list[str]) -> list[list[str]]:
    contentToPathFiles = collections.defaultdict(list)

    for path in paths:
      words = path.split(' ')
      rootPath = words[0]  # "root/d1/d2/.../dm"
      for fileAndContent in words[1:]:  # "fn.txt(fn_content)"
        l = fileAndContent.find('(')
        r = fileAndContent.find(')')
        # "fn.txt"
        file = fileAndContent[:l]
        # "fn_content"
        content = fileAndContent[l + 1:r]
        # "root/d1/d2/.../dm/fn.txt"
        filePath = rootPath + '/' + file
        contentToPathFiles[content].append(filePath)

    return [filePath for filePath in contentToPathFiles.values() if len(filePath) > 1]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.