File access System
I was asked the following question. If given the folder access tree and given query folder name, return TRUE|FALSE is user have access to it.
for eg. below - C and E have access. Then if we check for F, it should have access too. Same for G. cause F is child of E and G is child of F.
/*
A
|___ B
| |___ C <-- access
| |___ D
|___ E <-- access
|___ F
|
-- G <--acesss
*/Follow up: access = {'C', 'E', 'G') but 'G' is redunant. How to shorten the access list.I provided a working solution to the question:
It worked fine. For the initial questions and for the follow up too. All the test cases passed. Still got an automated reject. Not sure what they are expecting.
NVM. it was ok experience. I was happy that it went well. but oh well!
Please feel free to point out the errors in the code. Would be good learning for me.
My solution:
class FileSystem{
Map<String,String> map;
Set<String> access;
public FileSystem(List<List<String>> folders, Set<String> access) {
this.access = access;
map = new HashMap<>();
for(List<String> folder:folders) {
String child = folder.get(0);
String parent = folder.get(1);
map.put(child,parent);
}
}
public boolean hasAccess(String file) {
if(access.contains(file)) return true;
while(map.containsKey(file)) {
file = map.get(file);
if (access.contains(file)) return true;
}
return false;
}
public Set<String> removeAccess() {
Set<String> setAccess = new HashSet<>(access);
for(String file: access) {
if(hasAccessChild(file)) setAccess.remove(file);
}
return setAccess;
}
private boolean hasAccessChild(String file) {
while(map.containsKey(file)) {
file = map.get(file);
if (access.contains(file)) return true;
}
return false;
}
}
class Solution {
public static void main(String[] args) {
List<List<String>> folders = new ArrayList<>();
folders.add(Arrays.asList("A", null));
folders.add(Arrays.asList("B", "A"));
folders.add(Arrays.asList("C", "B"));
folders.add(Arrays.asList("D", "B"));
folders.add(Arrays.asList("E", "A"));
folders.add(Arrays.asList("F", "E"));
folders.add(Arrays.asList("G", "F"));
Set<String> access = new HashSet<>();
access.add("A");
access.add("B");
FileSystem fs = new FileSystem(folders, access);
System.out.println(fs.hasAccess("G"));
System.out.println(fs.hasAccess("F"));
System.out.println(fs.hasAccess("A"));
System.out.println(fs.hasAccess("C"));
System.out.println(fs.removeAccess());
System.out.println(fs.hasAccess("G"));
System.out.println(fs.hasAccess("F"));
System.out.println(fs.hasAccess("A"));
System.out.println(fs.hasAccess("C"));
}
}