Google Interview Question
Java DevelopersCountry: United States
Works as long as there are no cycles
static class Node {
int id, weight;
Node parent;
List<Node> children = new ArrayList<>();
Node(int id) {
this.id = id;
}
}
private static final Map<Integer, Node> nodeGraph = new HashMap<>();
public static void parseCsvFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(s -> parseCsvRow(s));
}
}
private static void parseCsvRow(String row) {
String[] cells = row.split(",");
int id = Integer.parseInt(cells[0]);
int parent = !cells[1].isEmpty()
? Integer.parseInt(cells[1])
: -1;
int weight = Integer.parseInt(cells[2]);
createNode(id, parent, weight);
}
private static void createNode(int id, int parent, int weight) {
Node node = nodeGraph.computeIfAbsent(id, Node::new);
node.weight = weight;
Node parentNode = parent != -1
? nodeGraph.computeIfAbsent(parent, Node::new)
: null;
if (parentNode != null) {
parentNode.children.add(node);
node.parent = parentNode;
}
}
public static int subWeight(Node node) {
if (node == null) return 0;
int weight = node.weight;
for (Node child : node.children) {
weight += subWeight(child);
}
return weight;
}
Works as long as there are no cycles
static class Node {
int id, weight;
Node parent;
List<Node> children = new ArrayList<>();
Node(int id) {
this.id = id;
}
}
private static final Map<Integer, Node> nodeGraph = new HashMap<>();
public static void parseCsvFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(s -> parseCsvRow(s));
}
}
private static void parseCsvRow(String row) {
String[] cells = row.split(",");
int id = Integer.parseInt(cells[0]);
int parent = !cells[1].isEmpty()
? Integer.parseInt(cells[1])
: -1;
int weight = Integer.parseInt(cells[2]);
createNode(id, parent, weight);
}
private static void createNode(int id, int parent, int weight) {
Node node = nodeGraph.computeIfAbsent(id, Node::new);
node.weight = weight;
Node parentNode = parent != -1
? nodeGraph.computeIfAbsent(parent, Node::new)
: null;
if (parentNode != null) {
parentNode.children.add(node);
node.parent = parentNode;
}
}
public static int subWeight(Node node) {
if (node == null) return 0;
int weight = node.weight;
for (Node child : node.children) {
weight += subWeight(child);
}
return weight;
}
1. Sort all nodes based on the parent id.
2. Processes getChildren returns the first and last index of children of the parent by doing binary search on the list for the parent ID. It takes O(lg n) time.
3. Recursively print out the all the subweights by calling the subweight procedure on the root.
subweight(root)
if root = null
return 0
children <- getChildren(root.ID)
childrenWeights <- 0
for child in children
childrenWeights <- childrenWeights + subweight(child)
return root.weight + childrenWeights
in total it takes O(n lg n) time and O(n) memory.
- Anonymous February 14, 2018