Google Interview Question for Software Engineer / Developers


Country: Berling
Interview Type: Phone Interview




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

The idea is to first find all the bin cells, and add then to a queue. You can then do a flood fill for every iteration through the queue where you add the neighbours of each cell to said queue as you go. See Python implementation below (assumes by 'distance' you meant manhattan distance):

from collections import deque

def get_dist_to_bin(M: list[list[int]]) -> D list[list[int]]:
	r, c = len(M), len(M[0])  # row, cols
	bins = deque()

	for i in range(r):
		for j in range(c):
			if M[i][j]:
				continue

			if    i and M[i-1][j]: dq.append( (i,j) )
			elif j and M[i][j-1]: dq.append( (i,j) )
			elif i<r-1 and M[i+1][j]: dq.append( (i,j) )
			elif j<c-1 and M[i][j+1]: dq.append( (i,j) )

	D = [[0]*c for _ in range(r)]  #initialize output

	curr_dist = 0
	curr_cnt = len(bins)
	while bins:
		i, j = dq.popleft()
		D[i, j] = curr_dist
		curr_cnt  -= 1

		if    i and not D[i-1][j]: dq.append( (i-1,j) )
		elif j and not D[i][j-1]: dq.append( (i,j-1) )
		elif i<r-1 and not D[i+1][j]: dq.append( (i+1,j) )
		elif j<c-1 and not D[i][j+1]: dq.append( (i,j+1) )
		
		if not curr_cnt: #finishes layer
			curr_dist += 1
			curr_cnt = len(bins)

	return D

- Anonymous December 03, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from collections import deque

def get_dist_to_bin(M: list[list[int]]) -> D list[list[int]]:
r, c = len(M), len(M[0]) # row, cols
bins = deque()

for i in range(r):
for j in range(c):
if M[i][j]:
continue

if i and M[i-1][j]: dq.append( (i,j) )
elif j and M[i][j-1]: dq.append( (i,j) )
elif i<r-1 and M[i+1][j]: dq.append( (i,j) )
elif j<c-1 and M[i][j+1]: dq.append( (i,j) )

D = [[0]*c for _ in range(r)] #initialize output

curr_dist = 0
curr_cnt = len(bins)
while bins:
i, j = dq.popleft()
D[i, j] = curr_dist
curr_cnt -= 1

if i and not D[i-1][j]: dq.append( (i-1,j) )
elif j and not D[i][j-1]: dq.append( (i,j-1) )
elif i<r-1 and not D[i+1][j]: dq.append( (i+1,j) )
elif j<c-1 and not D[i][j+1]: dq.append( (i,j+1) )

if not curr_cnt: #finishes layer
curr_dist += 1
curr_cnt = len(bins)

return D

- Anonymous March 27, 2022 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

```py
import numpy as np
import pandas as pd

def is_bin_cell(x, y, matrix):
try:
up = matrix[x-1][y] if x > 0 else 0
except:
up = 0

try:
down = matrix[x+1][y] if x < len(matrix) else 0
except:
down = 0

try:
matrix[x][y-1] if y > 0 else 0
except:
down = 0

try:
left = matrix[x][y-1] if y > 0 else 0
except:
left = 0

try:
right = matrix[x][y+1] if y < len(matrix[0]) else 0
except:
right = 0

if (matrix[x][y] == 0) and (1 in [up, down, right, left]):
return True
return False


def get_bin_cells(matrix):
bindexes = []
for i, row in enumerate(matrix):
for j, _ in enumerate(row):
if is_bin_cell(i, j, matrix):
bindexes.append((i, j))
return bindexes


def euclidean(i, j, matrix):
p1, p2 = i
d1, d2 = j
return (((matrix[p1][0] - matrix[d1][0])**2) + ((matrix[p2][1] - matrix[d2][1])**2)) ** .5


def get_distances(matrix):
bin_cells = get_bin_cells(matrix)
distances = {}
for i, row in enumerate(matrix):
for j, _ in enumerate(row):
distances[f'({i}, {j})'] = [euclidean((i, j), t, matrix) for t in bin_cells]

return distances

# driver code
data = get_distances(matrix)
index = [str(i) for i in data]
rows = [[coord] + i for coord, i in zip(index, data.values())]
pd.DataFrame(rows, columns=['Coord']+get_bin_cells(matrix))
```

- Beelzebruno March 31, 2022 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

vector<vector<int>> minBinDistance(const vector<vector<int>>& matrix) {

   vector<vector<int>> dist;
   int n = matrix.size();
   if(n == 0) return dist;
   int m = matrix[0].size();
   if(m == 0)return dist;

     dist.resize(n,vector<int>(m,1e9));  
     queue<vector<int>> bfsQ;   // queue will store { row , col , steps } in array form 

    for(int i=0;i<n;i++){
      for(int j=0; j<m ; j++){
            if(matrix[i][j] == 1) 
            {
              dist[i][j] = 0;
              bfsQ.push({i,j,0});  // { row , col , steps }
           }
        }
    }

   if(bfsQ.empty()) return dist;


  int dx[] = {0,0,1,-1};
  int dy[] = {1,-1,0,0};



   while(!bfsQ.empty()) {
      vector<int> front = bfsQ.front(); 
      bfsQ.pop();
      int row = front[0] , col = front[1] , steps = front[2] ;
      for(int dir=0;dir<4;dir++){
         int newRow = row + dx[dir];
         int newCol = col + dy[dir];
         if(newRow >=0 && newCol >= 0 && newRow < n && newCol < m ) {
             int totalSteps = steps + 1;
             if(dist[newRow][newCol] > totalSteps ) {
                dist[newRow][newCol] = totalStesp ; 
               bfsQ.push({ newRow , newCol , totalSteps });       
             }
         }
      }

  }

   return dist ; 

}

- C++ | BFS October 17, 2023 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

vector<vector<int>> minBinDistance(const vector<vector<int>>& matrix) {

vector<vector<int>> dist;
int n = matrix.size();
if(n == 0) return dist;
int m = matrix[0].size();
if(m == 0)return dist;

dist.resize(n,vector<int>(m,1e9));
queue<vector<int>> bfsQ; // queue will store { row , col , steps } in array form

for(int i=0;i<n;i++){
for(int j=0; j<m ; j++){
if(matrix[i][j] == 1)
{
dist[i][j] = 0;
bfsQ.push({i,j,0}); // { row , col , steps }
}
}
}

if(bfsQ.empty()) return dist;


int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};



while(!bfsQ.empty()) {
vector<int> front = bfsQ.front();
bfsQ.pop();
int row = front[0] , col = front[1] , steps = front[2] ;
for(int dir=0;dir<4;dir++){
int newRow = row + dx[dir];
int newCol = col + dy[dir];
if(newRow >=0 && newCol >= 0 && newRow < n && newCol < m ) {
int totalSteps = steps + 1;
if(dist[newRow][newCol] > totalSteps ) {
dist[newRow][newCol] = totalStesp ;
bfsQ.push({ newRow , newCol , totalSteps });
}
}
}

}

return dist ;

}

- Anonymous October 17, 2023 | 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