Google Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
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
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.
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;
}
#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;
}
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?
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.
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']
])
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.
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;
}
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[0].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;
}
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
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[0].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[0].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[0].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<>());
redges.add(j);
row.put(i, redges);
Set<Integer> cedges = col.getOrDefault(j, new HashSet<>());
cedges.add(i);
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;
}
}
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)
{
int n = adj.size();
vector<int> realEdgesCounter(n);
priority_queue<pair<int, int>> pq;
for (int i = 0; i < n; ++i)
{
realEdgesCounter[i] = adj[i].size();
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;
for (int i: adj[vertex])
{
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[0].size(); ++j)
{
if (matrix[i][j] == 'O')
orbs.push_back({i, j});
}
}
int n = orbs.size();
vector<vector<int>> adj(n, vector<int>());
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))
{
adj[i].push_back(j);
}
}
}
int res = deleteMaxOrbs(adj);
cout << "Deleted: " << res << endl;
return 0;
}
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 28, 2018