Google Interview Question for Software Engineers


Country: United States




Comment hidden because of low score. Click to expand.
3
of 5 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!

- aonecoding4 November 18, 2018 | Flag Reply
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
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;
}

- PeyarTheriyaa November 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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

- aabb November 27, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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

- PeyarTheriyaa April 14, 2019 | Flag
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.

- pkp November 18, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- abedillon November 19, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- Victor January 02, 2019 | Flag
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")

- abedillon November 19, 2018 | Flag Reply
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

- eugene.kazaev November 23, 2018 | Flag Reply
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;
}

- Siddharth Yadav December 12, 2018 | Flag Reply
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)

- just_idea May 02, 2019 | Flag Reply
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.

- nooooob May 31, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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
}

- BW January 03, 2021 | Flag Reply
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.

- Anonymous November 18, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- abedillon November 19, 2018 | Flag


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More