Google Interview Question

Judge if a Sudoku solution is right.

Interview Answers

Anonymous

Feb 11, 2012

@Gabriel, but you still need to scan the board, right? That's still O(n^2) IMHO.

1

Anonymous

Apr 20, 2012

I think it's actually O(3*9) time plus O(9) space, count sorting each row, column and 3x3 square. If even one of the integer in each row, column or square is counted twice you can just return false. If the counts succeed in all three cases then return true.

Anonymous

Apr 20, 2012

By the way, if the sudoku is not 3 * 3 based, but k * k, then you have O(3 * k * k) time (count sorting each row, column and square) and O(k * k) space.

Anonymous

Apr 25, 2012

def validate(grid): results = [0] * 27 for i, v in enumerate(grid): for j, w in enumerate(v): box = j/3 + (i/3)*3 results[i] |= 1 << w-1 results[9+j] |= 1 << w-1 results[18+box] |= 1 << w-1 return len([1 for i in results if i == 511]) == 27 # 511 == 111111111

Anonymous

Feb 4, 2012

@Interview Candidate , I don't think your solution is correct, because there is a nother requirment which is that every 3X3 part is also 1-9, so the complexity becomes n^3. @Gabriel, I don't understand your solution, can you make it clearer?

Anonymous

Dec 7, 2011

I use two loop to do the judgement and the time complexity is O(n^2)

Anonymous

Dec 19, 2011

It can be done in O(n) really easy :). you need 27 variables (int). And based on the coordinates in the sudoku table you update for each value 3 of these by setting the corresponding bit to 1. At the end in order to check the validity of the solution, it just needs all those 27 variables to be 111111111(2). If not, then you have no solution! Implementing is straightforward!