I completed the following question but it seems a lot of space complexity.
Do you think is there a way to complete it with graph search or so?
Thanks for the comments.
Suppose we have some input data describing a graph of relationships between parents and children over multiple generations. The data is formatted as a list of (parent, child) pairs, where each individual is assigned a unique positive integer identifier.
For example, in this diagram, 3 is a child of 1 and 2, and 5 is a child of 4:
1 2 4 15
\ / / | \ /
3 5 8 9
\ / \ \
6 7 11
Sample input/output (pseudodata):
parentChildPairs = [ (1, 3), (2, 3), (3, 6), (5, 6), (15, 9), (5, 7), (4, 5), (4, 8), (4, 9), (9, 11) ]
Write a function that takes this data as input and returns two collections: one containing all individuals with zero known parents, and one containing all individuals with exactly one known parent.
Output may be in any order:
findNodesWithZeroAndOneParents(parentChildPairs) => [
[1, 2, 4, 15], // Individuals with zero parents
[5, 7, 8, 11] // Individuals with exactly one parent
]
Complexity Analysis variables:
n: number of pairs in the input
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ParentChild2 {
public static void main(String[] argv) {
int[][] parentChildPairs = new int[][] {
{1, 3}, {2, 3}, {3, 6}, {5, 6}, {15, 9}, {5, 7},
{4, 5}, {4, 8}, {4, 9}, {9, 11}
};
List<List<Integer>> list = findNodesWithZeroAndOneParents(parentChildPairs);
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
static List<List<Integer>> findNodesWithZeroAndOneParents(int[][] parentChildPairs){
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> childMap = new HashMap<>();
Map<Integer, Integer> parentMap = new HashMap<>();
for(int i=0;i<parentChildPairs.length; i++){
if(!childMap.containsKey(parentChildPairs[i][1])){
childMap.put(parentChildPairs[i][1], 1);
} else{
int value = childMap.get(parentChildPairs[i][1]);
childMap.put(parentChildPairs[i][1], value + 1);
}
}
for(int i=0;i<parentChildPairs.length;i++){
if(!childMap.containsKey(parentChildPairs[i][0])){
parentMap.put(parentChildPairs[i][0], 1);
}
}
ArrayList<Integer> temp2 = new ArrayList<>();
for( Map.Entry<Integer, Integer> entry: parentMap.entrySet()){
if(entry.getValue() == 1){
temp2.add(entry.getKey());
}
}
result.add(temp2);
ArrayList<Integer> temp = new ArrayList<>();
for( Map.Entry<Integer, Integer> entry: childMap.entrySet()){
if(entry.getValue() == 1){
temp.add(entry.getKey());
}
}
result.add(temp);
return result;
}
}