Google Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




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

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!

def solve(board):
    m, n = len(board), len(board[0])
    '''create adjacency list
    rows[0] has all the nodes in 1st row
    rows[1] has all the nodes in 2nd row
    etc.
    cols[0] has all the nodes in 1st column
    cols[1] has all the nodes in 2nd column
    etc.'''
    rows, cols = [set() for i in range(m)], [set() for j in range(n)]
    for i in range(m):
        for j in range(n):
            if board[i][j] is 'O':
                rows[i].add(j)
                cols[j].add(i)

    #count the degree (number of neighbors) of every orb
    degrees = dict()
    for i in range(m):
        for j in rows[i]:
            degree = len(rows[i]) + len(cols[j]) - 2
            if degree > 0:
                degrees[(i, j)] = degrees

    #erase the node with minimum positive degree until all nodes have 0 degree
    while degrees:
        erase_orb(degrees, board, rows, cols)

    #output
    for row in board:
        print row


#erase the orb with the minimum degree
def erase_orb(degrees, board, rows, cols):
    #find the node with minimum positive degree
    i, j = min(degrees.items(), key=lambda x: x[1])[0]
    #erase this node
    rows[i].remove(j)
    cols[j].remove(i)
    degrees.pop((i, j))
    board[i][j] = 'X'
    print 'erase ', (i, j)

    #remove one degree from every neighbor of the node erased
    for y in rows[i]:
        degrees[(i, y)] -= 1
        if degrees[(i, y)] is 0:
            degrees.pop((i, y))

    for x in cols[j]:
        degrees[(x, j)] -= 1
        if degrees[(x, j)] is 0:
            degrees.pop((x, j))


solve([
    ['X', 'X', 'X', 'X', 'X', 'O'],
    ['O', 'X', 'X', 'X', 'X', 'X'],
    ['O', 'X', 'X', 'X', 'X', 'O'],
    ['X', 'X', 'O', 'X', 'O', 'X'],
    ['X', 'O', 'X', 'X', 'X', 'O']
    ])

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

What if there's more than one node with the minimum degree, say in the same row or column? Your code seems to just take the first node with the minimum degree.

- divm01986 January 08, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(N^2) time, O(N^2) memory

int playOrbGame(vector<vector<bool>>& orbs)
{
	if (orbs.empty() || orbs[0].empty())
	{
	  return 0;
	}
	auto N = orbs.size();
	auto M = orbs[0].size();
	vector<vector<int>> orb_column_sums(N, vector<int>(M,0));
	for(size_t i = N - 2; i + 1 > 0; --i)
	{
	  for(size_t j = 0; j < M; ++j)
	  {
		orb_column_sums[i][j] = orbs[i+1][j] ? orb_column_sums[i+1][j] + 1 : orb_column_sums[i+1][j];
	  }
	}
	int orbs_left = 0;
	for(size_t i = 0; i < N; ++i)
	{
	  int min_column_orbs = max(M,N) + 1;
	  int column_to_keep_orb = -1;
	  for (size_t j = 0; j < M; ++j)
	  {
	    if (!orbs[i][j])
		{
		  continue;
		}
		if (orb_column_sums[i][j] < min_column_orbs)
		{
		  min_column_orbs = orb_column_sums[i][j];
		  column_to_keep_orb = j;
		}
	  }
	  if (column_to_keep_orb != -1)
	  {
		++orbs_left;
	    for(size_t k = i + 1; k < N; ++k)
		{
		  orbs[k][column_to_keep_orb] = false;
		}
		for(size_t l = 0; l < M; ++l)
		{
		  if (l != column_to_keep_orb)
		  {
		    orbs[i][l] = false;
		  }
		}
	  }
	}
	return orbs_left;
}

- Antake December 02, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

just to see all the zeros that are connected will be in a single component.
So from a connected component of Zeros we only require one zero from that component.
So the answers it the no of connected component.
Can be done in O(N^2) time to add everything in union find by path compression.
0(N^2) space

- googleHelper December 03, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does finding the connected component work for this ?

OXOXXO
XXOXXO
XXXXOX

The connected components solutions would return 2 but the expected solution is 3

Let me know if I am missing something obvious.

- Anonymous December 31, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

For the following example:
OXOXXO
XXOXXO
XXXXOX

The expected solution should be 2, as you would erase in the following order:
(1, 2), (1, 5), (0, 5), (0, 2) which leaves only (0, 0) and (2, 4).

- Anonymous January 04, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <bits/stdc++.h>

using namespace std;
typedef long long LL;
typedef pair<int,int> pii;

#define forup(i,a,b) for(i=(a); i<(b); ++i)
#define fordn(i,a,b) for(i=(a); i>(b); --i)
#define rep(i,a) for(i=0; i<(a); ++i)

#define gi(x) scanf("%d",&x)
#define gl(x) cin>>x
#define gd(x) scanf("%lf",&x)
#define gs(x) scanf(" %s",x)

#define fs first
#define sc second

#define pb push_back
#define mp make_pair

const int inf=numeric_limits<int>::max();
const LL linf=numeric_limits<LL>::max();

const int max_n=100;

int n;

char arr[max_n][max_n], com[max_n][max_n];

void dfs(int y, int x, int comp){
    int i;
    com[y][x] = comp;
    forup(i, y+1, n){
        if(arr[i][x] == 'O' && !com[i][x])
            dfs(i, x, comp);
    }
    forup(i, x+1, n){
        if(arr[y][i] == 'O' && !com[y][i])
            dfs(y, i, comp);
    }
}

int main() {
    int i, j, k, comp;
    gi(n);
    rep(i, n){
            scanf("%s", arr[i]);
    }

    comp = 0;

    rep(i, n){
        rep(j, n){
            if(arr[i][j] == 'O' && !com[i][j])
                dfs(i, j, comp++);
        }
    }
    printf("%d\n", --comp);
    return 0;
}

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

A simple solution involving Os in same row/column as a connected in a graph. dfs to find the number of connected components. Can be written better with iterative dfs maybe?

- happysingshappy December 22, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does finding the connected component work for this ?

OXOXXO
XXOXXO
XXXXOX

The connected components solutions would return 2 but the expected solution is 3

Let me know if I am missing something obvious.

- Anonymous December 31, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does finding the connected component work for this ?

OXOXXO
XXOXXO
XXXXOX

The connected components solutions would return 2 but the expected solution is 3

Let me know if I am missing something obvious.

- Anonymous December 31, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def connected_components_grid(grid):

    connected_components = 0

    for x in xrange(len(grid)):
        for y in xrange(len(grid[x])):
            if grid[x][y] == "O":
                dfs_from_cell(grid,x,y)
                connected_components += 1
    
    return connected_components

def dfs_from_cell(grid, x, y):

    grid[x][y] = "O_x"

    for i in xrange(len(grid)):
        if grid[i][y] == 'O':
            grid[i][y] = "O_x"
            dfs_from_cell(grid,i,y)
    
    for i in xrange(len(grid[x])):
        if grid[x][i] == 'O':
            grid[x][i] = "O_x"
            dfs_from_cell(grid,x,i)



print connected_components_grid([
    ['X', 'X', 'X', 'X', 'X', 'O'],
    ['O', 'X', 'X', 'X', 'X', 'X'],
    ['O', 'X', 'X', 'X', 'X', 'O'],
    ['X', 'X', 'O', 'X', 'O', 'X'],
    ['X', 'O', 'X', 'X', 'X', 'O']
    ])

- Javi January 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

First, create a Graph of all the orbs, such that there is an edge between two orbs, if they share a row or a column.

The basic idea is that you can always pick all the orbs from each connected component of the graph, except one.

So, if there are n different connected components, the answer would be :
number of stones - number of connected components.

You can use DFS or Union-Find to find number of connected components.

- Nitin January 06, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Time Complexity: O(C( n *m, Math.max(m,n)))
Space: O(n + m)

Approach: Iterate through each row and select an orb that will be chosen to stay in the final board. When selecting an orb in the row, make sure it’s not in the same column as another orb that was previously selected

int minOrbs(char[][] m) {
	boolean[] cols = new boolean[m[0].length];
	return minOrbsHelp(m, cols, 0);
}


int minOrbsHelp(char[][] m, boolean[] visited, int idx) {
	if (idx == m.length) {
		return 0;
	}

	boolean allChosen = true;
	int result = Integer.MAX_VALUE;
	for (int c = 0; c < m[0].length; c++ ) {
		if (m[r][c] == ‘O’ && !visited[c]) {
			allChosen = false;
			visited[c] = true;
			result = Math.min(result, 1 + minOrbsHelp(m, visited, idx + 1);
			visited[c] = false;

		}

	}

	if (allChosen) {
		return minOrbsHelp(m, visited, idx + 1);

	}

	return result;

}

- divm01986 January 08, 2019 | Flag Reply


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