## Google Interview Question for Software Engineers

Country: United States

Comment hidden because of low score. Click to expand.
2
of 4 vote

Solution:

``````int moveCoins(TreeNode root) {
return dfs(root, new HashMap<>());
}

int dfs(TreeNode n, Map count) {
if(!count.containsKey(n)) {
count.put(n, n.val);
}
int coinsNum = count.get(n);
int res = 0;
for(TreeNode kid : n.children) {
res += dfs(kid, count);
coinsNum += count.get(kid);
res += Math.abs(count.get(kid));
}
count.put(n, coinsNum - 1);
return res;
}``````

Looking for interview experience sharing and coaching?

Visit 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!

Comment hidden because of low score. Click to expand.
1
of 1 vote

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
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;
}``````

Comment hidden because of low score. Click to expand.
0

I don't understand the Math.abs(t)
When does a value ever go negative here?

Comment hidden because of low score. Click to expand.
0

if the sub tree has zero coins in the node that means we have to bring one coin to that node essentially meaning deficit of (i.e. -1 of) coins be it deficit or surplus the coin needs to be moved so -1 requires 1 move

Comment hidden because of low score. Click to expand.
0
of 0 vote

Question is ambiguous. Not given whether it is a binary tree, BST or any such thing.

Comment hidden because of low score. Click to expand.
0

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.

Comment hidden because of low score. Click to expand.
0

Based on what I have understood about the question, it does not matter how many children each node has. The solution should be generic enough to capture all type of trees.

Comment hidden because of low score. Click to expand.
0
of 0 vote

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")``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````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``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````#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;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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)

Comment hidden because of low score. Click to expand.
0
of 0 vote

A parent should first move coins to its children, and the remaining to its parent. If it is done the other way then the sibling of the parent or even child has to move coin through parent, that will take more moves.

Comment hidden because of low score. Click to expand.
-2
of 2 vote

Question asks ofr minimum number of moves. That's 0 if the coins are already distributed.

Comment hidden because of low score. Click to expand.
0

No. It's asking for the minimum moves *given a tree* so it's a function that takes a tree and outputs the number of moves it takes to evenly distribute the coins on that tree.

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.