Zillow Interview Question
Country: United States
I think you can store each line as an integer, that is composed by 32 bits. You can use each bit of the integer to represents a single square, if the bit is 0 then the square contains a O if it is 1 the square contains an X. In this case you would need 2^31 Integers to store the entire board. You can preprocess the board to store each configuration as "winning for X", "winning for O" or "Draw".
The size of the grid is 2^31 x 2^31 so you need 2^31 bits, not an integer that can go up to 2^31. For one line, you'd need 2^31/32 integers, which is a bit too much memory-wise.
An integer is composed by 32 bit, so the lowlevel representation of an integer will be 10011010100100100......11001010, thus I think you can use just one integer to represent up to 32 squares. I assumed that we had to represent final configurations of the game to check if there is the winner, then each square will be filled with X or O. we need just 2 values that means that each square can be represented with just 1 bit. If the integer has 32 bits you can represent each line with 1 integer
2 Arrays of 32 integers each.
In one array, the rows are stored, blanks are represented by 0
In another, the columns are stored, blanks are represented by 1
This is so that, the empty cells can be distinguished
Obviously, we can store 4 kind of lines consists of x or o signs. This is horizontal, vertical, and two diagonal kind of lines. For each line, store coordinates of its ends. Also, maintain hash table to map coordinates to collection of lines ending in particular point.
When putting particular symbol to some point, extract up to 8 lines ending at that point and update set of lines on the map in O(1) time.
Checks for winner in O(1) time.
It is 2*2^31*2^31/32 ----> that is 2 arrays, each with (2^31 arraylength) no of rows and each row contains ((2^31)/32 ( integers)) as columns.
- nikprashanth July 10, 2016To represent the state, we need say 00 for 'O' and 11 for 'X' and 01 or 10 for 'empty'.
So one array stores the state of O as 0 and rest as1s,
and in, Other array store the stae of X as 1 and rest as 0s.
Now by superimposing both together you can get the logic!