609. Find Duplicate File in System
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to identify groups of duplicate files from a given list of directory information strings. Each string contains a directory path and a series of file entries, where each entry specifies a file name and its content. A group of duplicate files consists of two or more files that have the exact same content. The goal is to return a list of these groups, where each group is a list of the full paths to the duplicate files.
Solution
Find Duplicate File in System in Python
from collections import defaultdict
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
# Use defaultdict to automatically handle list creation for new keys
content_map = defaultdict(list)
# Iterate through each directory info string
for path_info in paths:
# Split the string by space. The first element is the directory path,
# the rest are file descriptions.
parts = path_info.split(' ')
directory = parts[0]
# Process each file description
for file_info in parts[1:]:
# Find the index of '(' to separate name from content
open_paren_idx = file_info.find('(')
file_name = file_info[:open_paren_idx]
# Content is between '(' and ')'. The `[:-1]` removes the trailing ')'
content = file_info[open_paren_idx+1:-1]
# Construct the full file path
full_path = f"{directory}/{file_name}"
# Add the full path to the map under its content
content_map[content].append(full_path)
# Filter the map to find groups of duplicates
# A group must have more than one file path
result = [file_list for file_list in content_map.values() if len(file_list) > 1]
return result
Find Duplicate File in System in Java
class Solution {
public List<List<String>> findDuplicate(String[] paths) {
// Map to store content as key and list of file paths as value
Map<String, List<String>> contentMap = new HashMap<>();
// Iterate through each directory info string
for (String pathInfo : paths) {
// Split the string by space to separate directory and files
String[] parts = pathInfo.split(" ");
String directory = parts[0];
// Start from index 1 to process file descriptions
for (int i = 1; i < parts.length; i++) {
String fileInfo = parts[i];
// Find the index of '(' to separate name and content
int openParenIndex = fileInfo.indexOf('(');
String fileName = fileInfo.substring(0, openParenIndex);
// Extract content, which is between '(' and ')'
String content = fileInfo.substring(openParenIndex + 1, fileInfo.length() - 1);
// Construct the full file path
String fullPath = directory + "/" + fileName;
// Get the list of paths for this content, or create a new one
List<String> fileList = contentMap.getOrDefault(content, new ArrayList<>());
fileList.add(fullPath);
contentMap.put(content, fileList);
}
}
// Prepare the result list
List<List<String>> result = new ArrayList<>();
// Iterate through the map values to find groups of duplicates
for (List<String> fileList : contentMap.values()) {
// A group of duplicates must have at least two files
if (fileList.size() > 1) {
result.add(fileList);
}
}
return result;
}
}
Find Duplicate File in System in C++
class Solution {
public:
vector<vector<string>> findDuplicate(vector<string>& paths) {
// Map to store content as key and list of file paths as value
unordered_map<string, vector<string>> contentMap;
// Iterate through each directory info string
for (const string& pathInfo : paths) {
stringstream ss(pathInfo);
string part;
string dir;
// The first part is the directory path
getline(ss, dir, ' ');
// The subsequent parts are file descriptions
while (getline(ss, part, ' ')) {
// Find the position of '(' to separate file name and content
size_t open_paren = part.find('(');
string fileName = part.substr(0, open_paren);
// Extract content, which is between '(' and ')'
// Length of content is part.length() - open_paren - 2
string content = part.substr(open_paren + 1, part.length() - open_paren - 2);
// Construct the full file path
string fullPath = dir + '/' + fileName;
// Add the full path to the map under its content
contentMap[content].push_back(fullPath);
}
}
// Prepare the result vector
vector<vector<string>> result;
// Iterate through the map to find groups of duplicates
for (auto const& [content, fileList] : contentMap) {
// A group of duplicates must have at least two files
if (fileList.size() > 1) {
result.push_back(fileList);
}
}
return result;
}
};
Find Duplicate File in System in TypeScript
function findDuplicate(paths: string[]): string[][] {
// Map to store content as key and list of file paths as value
const contentMap = new Map<string, string[]>();
// Iterate through each directory info string
for (const pathInfo of paths) {
// Split the string by space to separate directory and files
const parts = pathInfo.split(' ');
const directory = parts[0];
// Start from index 1 to process file descriptions
for (let i = 1; i < parts.length; i++) {
const fileInfo = parts[i];
// Find the index of '(' to separate name and content
const openParenIndex = fileInfo.indexOf('(');
const fileName = fileInfo.substring(0, openParenIndex);
// Extract content, which is between '(' and ')'
const content = fileInfo.substring(openParenIndex + 1, fileInfo.length - 1);
// Construct the full file path
const fullPath = `${directory}/${fileName}`;
// Get the list of paths for this content, or create a new one
if (!contentMap.has(content)) {
contentMap.set(content, []);
}
contentMap.get(content)!.push(fullPath);
}
}
// Prepare the result array
const result: string[][] = [];
// Iterate through the map values to find groups of duplicates
for (const fileList of contentMap.values()) {
// A group of duplicates must have at least two files
if (fileList.length > 1) {
result.push(fileList);
}
}
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.