This is a question I havent seen on leetcode. Essentially, you are given a complete list of directories and files in the file system, and then a subset of files. Return an augmented list of the subset, where if all files in a directory are listed in the subset, replace those file names with the directory name.
Example input & output:
allFiles = [
"a/b/c/d.txt",
"a/b/c/e.txt",
"a/b/b.txt",
"a/b/e.txt",
"b/c/d.txt"
]
subsetFiles = [
"a/b/c/d.txt",
"a/b/c/e.txt",
"a/b/b.txt",
"b/c/d.txt"
]
output=[
"a/b/c",
"a/b/b.txt",
"b"
]
This is a solution I made after the interview, I wasn't able to code up a working solution within the time allotment. Please reply if you have a more efficient/effective solution, or if you can identify a similar problem on leetcode!
def consolidateFiles(allFiles,subFiles):
allFilesDirs = makeDirs(allFiles)
subFilesDirs = makeDirs(subFiles)
#sorting directories by length, want to check the larger directories first
dirs = sorted(list(subFilesDirs.keys()),key = lambda x:len(x))
outFiles = set(inFiles)
commonDirs = set()
for d in dirs:
# if we already know the directory "a/" is the same, we don't need to check "a/b/"
if any([d1 == d[:len(d1)] for d1 in commonDirs]):
continue
else:
if subFilesDirs[d] == allFilesDirs[d]:
for f in subFilesDirs[d]:
outFiles.remove(f)
outFiles.add(d)
commonDirs.add(d)
return outFiles
def makeDirs(files):
filesDirs = {}
for f in files:
prev = ""
dirs = []
for d in f.split('/')[:-1]:
d = prev+'/'+d
dirs.append(d)
prev = d
for d in dirs:
if d in filesDirs:
filesDirs[d].add(f)
else:
filesDirs[d] = set([f])
return filesDirs
```