Google Interview Question
Software EngineersCountry: United States
This is how I'd go about it
a node having excess coins or deficit of coins requires that many moves of coins from the connected node
so the deficit or excess is to be added to the no of moves the excess or deficit is moved to or from the parent
Note: assumptions made:
only one coin can be moved per move
only up or down one step of the tree
private static Node tree;
private static int moves;
public static void main(String[] args) {
// init tree here
moves = 0;
traverse(tree);
System.out.println("The number of moves required : " + moves);
}
private static int traverse(Node tmp) {
int ret = 0;
for (Node n : tmp.kids) {
int t = traverse(n);
ret += t;
moves += Math.abs(t);
}
ret += tmp.val - 1;
return ret;
}
This can be solved for a general tree. Perhaps a follow-up question would be to refine the algorithm for a specific kind of tree.
Each sub-tree will require a certain number of "moves" to ensure one coin in each node leaving and some "remainder" of extra or deficit coins at the root of the sub-tree. You count up all the moves of each sub-tree and add the absolute value of the "remainder":
class Tree:
def __init__(self, value, *children):
super().__init__()
self.value = value
self.children = children
def moves(self):
return abs(self.remainder()) + sum(child.moves() for child in self.children)
def remainder(self):
return 1 - self.value + sum(child.remainder() for child in self.children)
if __name__ == "__main__":
if __name__ == "__main__":
bbt = \
Tree(1,
Tree(1,
Tree(1),
Tree(1)),
Tree(1,
Tree(1),
Tree(1)))
assert bbt.moves() == 0, "balanced binary tree"
print("bbt good")
ll = \
Tree(0,
Tree(0,
Tree(0,
Tree(0,
Tree(5)))))
assert ll.moves() == 10, "linked list"
print("ll good")
mix = \
Tree(5,
Tree(0,
Tree(0),
Tree(0)
),
Tree(0,
Tree(0),
Tree(0)
),
Tree(0,
Tree(0),
Tree(5)
)
)
assert mix.moves() == 17, "mix"
print("mix good")
mix2 = \
Tree(5,
Tree(0,
Tree(0),
Tree(0)
),
Tree(0,
Tree(0),
Tree(0)
),
Tree(5,
Tree(0),
Tree(0)
)
)
assert mix2.moves() == 14, "mix2"
print("mix2 good")
struct Node {
let coins: Int
let children: [Node]
init(coins: Int = 0, children: [Node] = []) {
self.coins = coins
self.children = children
}
}
/* Tree:
0
2 1
0 3 0 0
1 0 0
*/
let tree = Node(coins: 0, children:
[Node(coins: 2, children: [Node(), Node()]),
Node(coins: 1, children: [
Node(),
Node(coins: 3, children: [Node(), Node(), Node()])
])
])
func traverse(node: Node) -> Int {
var value = node.coins == 0 ? 0 : (node.coins - 1)
for child in node.children {
value += traverse(node: child)
}
return value
}
print(traverse(node: tree)) // 3
#include <bits/stdc++.h>
#define ll long long
#define F first
#define S second
#define pb push_back
#define pii pair <int,int >
#define pll pair <ll,ll >
#define si(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
using namespace std;
const int N=1111;
const int MOD=1000000000+7;
std::vector<int > g[N];
int val[N];
pii dfs(int u,int par){
int sum=0,no_of_alive=0;
for(auto it: g[u]){
if(it==par)
continue;
pii temp=dfs(it,u);
sum+=temp.F+abs(temp.S);
no_of_alive+=temp.S;
}
return {sum,no_of_alive+1-val[u]};
}
int main(){
int n;
si(n);
for(int i=1;i<=n;i++){
si(val[i]);
}
for(int i=1;i<n;i++){
int a,b;
si(a),si(b);
g[a].pb(b);
g[b].pb(a);
}
pii f=dfs(1,1);
cout<<f.F;
return 0;
}
this can happen using depth first search and stack for parents and their counts.
if null, just return with zero moved needed
if leaf (left and right already handled), check if 1:
less than one borrow from the parent (top of the stack) (if -k, k+1 moves from the parent), return -(k+1) and add it to the counter of the top of the stack (parent)
more than one carry to parent the more than one (if k, k-1 moves to the parent) return k-1 and add it to the counter of the top of the stack (parent)
For the current node, process the children first and transfer coins from the node to its children and vice versa. It's OK if the node's coin balance gets negative, we'll handle it later by pulling more from the parent.
At this point the children are all balanced. Check our coin balance and transfer to/from the parent.
Any transfer, whether positive or negative, is tallied as positive. Therefore tally+=abs(t).
This is a standard post-order traversal, hence O(N).
type Node struct {
Coins int
Children []*Node
}
func BalanceTree(root *Node) (tally int) {
return BalanceNode(root, nil)
}
func BalanceNode(n *Node, p *Node) (tally int) {
for _, c := range n.Children {
tally += BalanceNode(c, n)
}
t := n.Coins - 1
if t < 0 {
tally += -t
} else {
tally += t
}
if p != nil {
p.Coins += t
}
return tally
}
Solution:
Looking for interview experience sharing and coaching?
- aonecoding4 November 18, 2018Visit AONECODE.COM for ONE-ON-ONE private lessons by FB, Google and Uber engineers!
SYSTEM DESIGN
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algorithms, Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Get hired from G, U, FB, Amazon, LinkedIn, Yahoo and other top-tier companies after weeks of training.
Email us aonecoding@gmail.com with any questions. Thanks!