27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 19 | Moderate<br />

19.2 Design an algorithm to figure out if someone has won in a game of tic-tac-toe.<br />

SOLUTION<br />

pg 89<br />

The first thing to ask your interviewer is whe<strong>the</strong>r <strong>the</strong> hasWon function will be called just<br />

once, or multiple times. If it will be called multiple times, you can get a very fast algorithm<br />

by amortizing <strong>the</strong> cost (especially if you can design your own data storage system for <strong>the</strong><br />

tic-tac-toe board).<br />

Approach #1: If hasWon is called many times<br />

There are only 3^9, or about twenty thous<strong>and</strong> tic-tac-toe boards. We can thus represent our<br />

tic-tac-toe board as an int, with each digit representing a piece (0 means Empty, 1 means<br />

Red, 2 means Blue). We set up a hashtable or array in advance with all possible boards as<br />

keys, <strong>and</strong> <strong>the</strong> values are 0, 1, <strong>and</strong> 2. Our function <strong>the</strong>n is simply this:<br />

Easy!<br />

int hasWon(int board) {<br />

return winnerHashtable[board];<br />

}<br />

Approach #2: If hasWon is only called once<br />

1 enum Piece { Empty, Red, Blue };<br />

2 enum Check { Row, Column, Diagonal, ReverseDiagonal }<br />

3<br />

4 Piece getIthColor(Piece[][] board, int index, int var, Check check) {<br />

5 if (check == Check.Row) return board[index][var];<br />

6 else if (check == Check.Column) return board[var][index];<br />

7 else if (check == Check.Diagonal) return board[var][var];<br />

8 else if (check == Check.ReverseDiagonal)<br />

9 return board[board.length - 1 - var][var];<br />

10 return Piece.Empty;<br />

11 }<br />

12<br />

13 Piece getWinner(Piece[][] board, int fixed_index, Check check) {<br />

14 Piece color = getIthColor(board, fixed_index, 0, check);<br />

15 if (color == Piece.Empty) return Piece.Empty;<br />

16 for (int var = 1; var < board.length; var++) {<br />

17 if (color != getIthColor(board, fixed_index, var, check)) {<br />

18 return Piece.Empty;<br />

19 }<br />

20 }<br />

21 return color;<br />

22 }<br />

23<br />

CareerCup.com<br />

2 6 6

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!