Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
I believe your last optimization is wrong: assume a correct configuration. Now swap two rows at the boundary of the top grid (could be any grid boundary). All rows and columns are going to be correct as before but the grid constraint is now incorrect (assuming the swapped rows are not identical)
public boolean isValid(int[][] m) {
int[][] t = new int[3][3];
int[] row = new int[10];
for (int i = 0; i < m.length; i++) {
int col = 0;
for (int j = 0; j < m.length; j++) {
/* assert value */
if(m[i][j] < 1 || m[i][j] > 9)
return false;
col += m[i][j];
t[i / 3][j / 3] += m[i][j];
row[i] += m[i][j];
if (col > 45 || t[i / 3][j / 3] > 45 || row[i] > 45)
return false;
}
}
return true;
}
acc. to me a simple soln would be. making a hasmap 9 hashmaps. per row. then 9 hashmaps per column and then 9 hashmaps per block. if we get any hashmap out of 27 hashmaps of those with lenght less than 9. then the soln is wrong. this is of complexity O(n) as no. of elements are 27 and we have 27 insert operations. we are making hashmaps of key as the value in cell and value can be left blank, in python this can also be done with the helps of sets.
boolean isValidAns(int[][] sudoku){
//Check the correctness for each row and column
for (int i = 0; i< sudoku.length; i++){
HashMap<Integer, Boolean> row = new HashMap<Integer,Boolean>();
HashMap<Integer, Boolean> column = new HashMap<Integer,Boolean>();
for (int j = 0; j< sudoku.length; j++){
if( row.get (sudoku[i][j]) | | column.get( sudoku[j][i])){
return false;
}else{
row.put( sudoku[i][j], true);
column.put(sudoku[j][i], true);
}
}
}
return true;
}
A simple solution would be
1. Make an array of n+1 size, with all elements initialized to zero
2. Scan first row and for every element, increase its count, then check the array if any element has count!=1, return false. Repeat the same for every row
3. Repeat the same for every column
At the end return true
this could be done without using the extra space as we know the sum of no in rows and columns and the no are also consecutive in rows and column as well as in 3x3 squares.
If you only concentrate over sum, then following suduku will also get passed with your approach.
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
Thus, minimum O(n) space is required to see if all elements are present or not in a row, column or 3x3 sub matrix.
If all the rows & all the columns have been checked for correctnes, then there is no need to check correctness of each grid.
- Aashish July 01, 2012