Question:
Given an input of a list of lists, each list contains a list of node_ids. The order of the list [A,B] represents a one way
connection from node A to node B, and node_ids that are the same between different lists are the same node.
We want to find the number of nodes in the longest chain across all the input lists.
Lets say we are given list -> ["A", "C", "D"], then A connected to C, and C connected to D. This
way we will be given list of lists which has several node links, we need to longest connected chain in this.
Input:
[["A", "C", "D"],
["A", "B", "E"],
["D", "F", "G", "H"],
["Z", "X", "C", "Q", "R"]]
Solution for longest chain - z, x, c, d, f, g, h
Output: 7My Solution, hope this helps someone. This is straight forward Topological Sort Question I think, please feel free to correct me or ask questions if you have doubts in my implementation. Thank you!
class Solution {
public int findLongestChain(List<List<String>> inputLists){
// map parent -> list(children)..
// map child -> parents (This is to get zero indegree elements, child that does not have parents)..
Map<String, List<String>> parentChild = new HashMap<>();
Map<String, List<String>> childParent = new HashMap<>();
for(List<String> list: inputLists){
for(int i=0; i<list.size()-1; i++){
parentChild.computeIfAbsent(list.get(i), k-> new ArrayList<>()).add(list.get(i+1));
if(i==0){
childParent.computeIfAbsent(list.get(i), k-> new ArrayList<>());
}
else{
childParent.computeIfAbsent(list.get(i+1), k-> new ArrayList<>()).add(list.get(i));
}
}
}
int maxSize = Integer.MIN_VALUE;
for(Map.Entry<String, List<String>> mapItem: childParent.entrySet()){
if(mapItem.getValue().size()==0){
int size = getChildList(parentChild, mapItem.getKey());
if(size > maxSize)
maxSize = size;
}
}
return maxSize;
}
public int getChildList(Map<String, List<String>> map, String input){
Queue<String> queue = new LinkedList<>();
Queue<Integer> sizeQueue = new LinkedList<>();
queue.offer(input);
sizeQueue.offer(1);
int maxSize = Integer.MIN_VALUE;
while(!queue.isEmpty()){
String node = queue.remove();
int size = sizeQueue.remove();
List<String> childList = map.get(node);
if(childList!=null){
for(String item:childList){
queue.offer(item);
size = size+1;
sizeQueue.offer(size);
}
}
else{
if(size>maxSize)
maxSize = size;
}
}
return maxSize;
}
public static void main(String[] args) {
List<List<String>> inputLists = new ArrayList<>();
inputLists.add(Arrays.asList("A", "C", "D"));
inputLists.add(Arrays.asList("A", "B", "E"));
inputLists.add(Arrays.asList("D", "F", "G", "H"));
inputLists.add(Arrays.asList("Z", "X", "C", "Q", "R"));
System.out.print(new Solution().findLongestChain(inputLists));
}
}