Google Interview Question for Software Engineers

Country: United States
Interview Type: In-Person

Comment hidden because of low score. Click to expand.
2
of 2 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)
rows has all the nodes in 1st row
rows has all the nodes in 2nd row
etc.
cols has all the nodes in 1st column
cols 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':

#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)
#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']
])``````

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

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.

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

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

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.

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

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).

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.empty())
{
return 0;
}
auto N = orbs.size();
auto M = orbs.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;
}``````

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

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

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?

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

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.

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

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.

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']
])``````

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.

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

}

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

public class pair{
int x,y;
public pair(int x,int y){
this.x = x;
this.y = y;
}
}
Public int minOrbs(char [ ][ ] mat){
int n = mat.length;
int m = mat.length;
boolean [ ][ ] visited = new boolean [n][m];
Stack<pair> s = new Stack<>();
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(mat[i][j] == 'O'){
s.push(new pair(i,j));
while(!s.isEmpty()){
pair temp = s.pop();
int x = temp.x;
int y = temp.y;
visited[x][y] = true;
for(int k=0;k<n;k++){
if(!visited[k][y] && mat[k][y]=='O'){
visited[k][y] = true;
s.push(new pair(k,y));
}
}
for(int k=0;k<m;k++){
if(!visited[x][k] && mat[x][k]=='O'){
visited[x][k] = true;
s.push(new pair(x,k));
}
}
if(!s.isEmpty()){
mat[x][y] = 'X';
}
}
ans++;
}
}
}
return ans;
}

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

1. First give a number for each orbs
OXOXXO 1X2XX3
XXXXXO -> XXXXX4
XXXXOX XXXX5X
2. Build a connection list for each orb to store all the other orbs connecting to this orb
1: 2, 3
2: 1, 3
3: 1, 2, 4
4: 3
5:
3. Choose one orb that have at least one connection but have least connections. Delete connection list of this orb. Then Delete this orb from other orbs' connection lists
1: 2, 3
2: 1, 3
3: 1, 2
5:

4. Repeat step 3
2: 3
3: 2
5:

3:
5:

5. Output the number of orb connection list left.
output=2

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

Cleaner and simpler approach;
Build graph,
run algorithm similar like Khan algo for topological sort;
Since, each connected orbit has at least 1 degree ( 1 edge between them).
So, if we find all the connected orbits to each other and run algo similar to khan, at the last only those orbit left which are no longer connect to any other;
Here is code

``````package Java;

import java.util.*;

/**
* Author: Nitin Gupta(nitin.gupta@walmart.com)
* Date: 12/04/19
* Description:
* e.g.
* <p>
* OXOXXO
* XXXXXO
* XXXXOX
* erase (0,0) and get
* XXOXXO
* XXXXXO
* XXXXOX
* erase (2,0) and get
* XXXXXO
* XXXXXO
* XXXXOX
* erase (5,0) and get
* XXXXXX
* XXXXXO
* XXXXOX
* no more moves available. Return 2 e.g.
* <p>
* OXOXXO
* XXXXXO
* XXOXOX
* erase(4,2), (2,2), (0,0), (2,0), (5,0)
* <p>
* Return 1
* e.g.
* OXOXXX
* XOXXXO
* XXXOOX
* <p>
* erase(0,0), (1,1), (3,2)
* <p>
* Return 3
*/

public class SetMatrixZeros {

static class DegreeNode {
int i, j;
int degree;

public DegreeNode(int i, int j, int degree) {
this.i = i;
this.j = j;
this.degree = degree;
}
}

public static void test(char matrix[][]) {
for (int i = 0; i < matrix.length; i++) {
System.out.println();
for (int j = 0; j < matrix.length; j++)
System.out.print(matrix[i][j] + " ");
}

System.out.println("\n\noutput");
int count = 0;
char result[][] = setMatrixZero(matrix);
for (int i = 0; i < result.length; i++) {
System.out.println();
for (int j = 0; j < result.length; j++) {
if (result[i][j] == 'O')
count++;
System.out.print(result[i][j] + " ");
}
}
System.out.println("\ncount :" + count);

}

public static void main(String args[]) {
char matrix[][] = {{'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'}};
test(matrix);

char matrix1[][] = {{'O', 'X', 'O', 'X', 'X'},
{'X', 'O', 'X', 'X', 'X', 'O'},
{'X', 'X', 'X', 'O', 'O', 'X'}};

test(matrix1);

char matrix2[][] = {{'O', 'X', 'O', 'X', 'O'},
{'X', 'X', 'X', 'X', 'X', 'O'},
{'X', 'X', 'O', 'X', 'O', 'X'}};

test(matrix2);

char matrix3[][] = {{'O', 'X', 'O', 'X', 'X', 'O'},
{'X', 'X', 'X', 'X', 'X', 'O'},
{'X', 'X', 'X', 'X', 'O', 'X'}};

test(matrix3);

}

private static char[][] setMatrixZero(char[][] matrix) {
Map<Integer, Set<Integer>> row = new HashMap<>();
Map<Integer, Set<Integer>> col = new HashMap<>();

int m = matrix.length;
int n = matrix.length;
//Build graph
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 'O') {
Set<Integer> redges = row.getOrDefault(i, new HashSet<>());
row.put(i, redges);

Set<Integer> cedges = col.getOrDefault(j, new HashSet<>());
col.put(j, cedges);
}

}
}

PriorityQueue<DegreeNode> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(o -> o.degree));

//Count degree
for (int i = 0; i < m; i++) {
for (Integer r : row.getOrDefault(i, new HashSet<>())) {
int degree = row.get(i).size() + col.getOrDefault(r, new HashSet<>()).size() - 2;
if (degree > 0)
priorityQueue.offer(new DegreeNode(i, r, degree));
}
}

int index;
//Delete till every node has zero degree except last node
while (true) {

DegreeNode node = priorityQueue.poll();

//decrease the degree
node.degree--;

//if it has more degree, then push it to process further
if (node.degree != 0)
priorityQueue.offer(node);
else {
//If all other node degree is 0? in that case only one node has more than 0 degree
if (priorityQueue.size() <= 1) {
break;
}
}

//Find and remove the degree
Set<Integer> rowsEdges = row.getOrDefault(node.i, new HashSet<>());
Set<Integer> colEdges = col.getOrDefault(node.j, new HashSet<>());

rowsEdges.remove(node.i);
if (rowsEdges.size() == 0)
row.remove(node.i);

colEdges.remove(node.j);
if (colEdges.size() == 0)
col.remove(node.j);

matrix[node.i][node.j] = 'X';

}

return matrix;
}

}``````

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

The key is delete the vertexes following the decreasing order of their degree.
It can be implemented using heaps, but in C++ priority queues don't have the decrease key method. A simple hack with a secondary vector need to be used:

``````int deleteMaxOrbs(vector<vector<int>> &adj)
{

vector<int> realEdgesCounter(n);
priority_queue<pair<int, int>> pq;

for (int i = 0; i < n; ++i)
{

if (realEdgesCounter[i] > 0)
pq.push({realEdgesCounter[i], i});
}

int deleted = 0;
while (!pq.empty())
{
int numEdges = pq.top().first;
int vertex = pq.top().second;
pq.pop();

if (numEdges == realEdgesCounter[vertex])
{
++deleted;
realEdgesCounter[vertex] = 0;

{
if (realEdgesCounter[i] > 0)
{
realEdgesCounter[i]--;

if (realEdgesCounter[i] > 0)
pq.push({realEdgesCounter[i], i});
}
}
}
}

return deleted;
}

int main()
{
vector<vector<char>> matrix =
{{'O', 'X', 'O', 'X', 'X', 'O'},
{'X', 'X', 'X', 'X', 'X', 'O'},
{'X', 'X', 'X', 'X', 'O', 'X'}};

vector<pair<int, int>> orbs;

for (int i = 0; i < matrix.size(); ++i)
{
for (int j = 0; j < matrix.size(); ++j)
{
if (matrix[i][j] == 'O')
orbs.push_back({i, j});
}
}

int n = orbs.size();

for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (i != j && (orbs[i].first == orbs[j].first ||
orbs[i].second == orbs[j].second))
{
}
}
}

cout << "Deleted: " << res << endl;

return 0;
}``````

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.