Skip to content

Instantly share code, notes, and snippets.

@dluciano
Created September 20, 2022 20:49
Show Gist options
  • Save dluciano/105bbda410016b114870827a217cd606 to your computer and use it in GitHub Desktop.
Save dluciano/105bbda410016b114870827a217cd606 to your computer and use it in GitHub Desktop.
609. Find Duplicate File in System
public class Solution {
const char Separator = ' ';
const char StartContentCharacter = '(';
const char EndContentCharacter = ')';
public IList<IList<string>> FindDuplicate(string[] paths) {
// [full file path, content]
static string GetFileName(in string fileAndContent) =>
fileAndContent[0..(fileAndContent.IndexOf(StartContentCharacter))];
static string GetFileContent(in string fileAndContent)=>
fileAndContent[(fileAndContent.IndexOf(StartContentCharacter) + 1)..fileAndContent.IndexOf(EndContentCharacter)];
string[][] GetFilesAndContent(in string path){
var s = path.Split(Separator);
var directory = s[0];
var filesAndContent = s[1..];
var res = new List<string[]>();
foreach(var fileAndContent in filesAndContent){
var fileName = GetFileName(fileAndContent);
var fileContent = GetFileContent(fileAndContent);
var fullPath = $"{directory}/{fileName}";
res.Add(new string[]{ fullPath, fileContent });
}
return res.ToArray();
}
// key: file content..., List<string> full file paths,
var duplicated = new Dictionary<string, List<string>>();
foreach(var path in paths){
var filesAndContent = GetFilesAndContent(path);
foreach(var fileAndContent in filesAndContent){
var fullFilePath = fileAndContent[0];
var content = fileAndContent[1];
if(!duplicated.ContainsKey(content))
duplicated[content] = new();
duplicated[content].Add(fullFilePath);
}
}
var duplicatedFiles = new List<IList<string>>();
foreach(var dup in duplicated.Values){
if(dup.Count <= 1)
continue;
var files = new List<string>();
foreach(var duplicatedFile in dup)
files.Add(duplicatedFile);
duplicatedFiles.Add(files);
}
return duplicatedFiles;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment