KatInterview

Three-in-a-Row: Find the Winner on a 3×3 Grid

Arrays & HashingAuto-graded · 20 test cases
HardAuto-gradedArrays & Hashingarraysgame-theorysimulation

Last updated

Tests whether you can encode all win conditions for a 3×3 grid as data and apply a uniform check to identify a winning player.

Three-in-a-Row: Find the Winner on a 3×3 Grid

You are given a snapshot of a 3×3 game grid stored as a flat list of 9 integers. Position i in the list maps to row i // 3 and column i % 3. Each cell holds one of three values:

  • 0 — the cell is empty
  • 1 — occupied by Player 1
  • 2 — occupied by Player 2

A player wins if they own every cell in any one row, any one column, or either of the two main diagonals.

Write a function that examines the board and returns:

  • 1 if Player 1 has a complete line
  • 2 if Player 2 has a complete line
  • 0 if neither player has won (whether the game is still in progress or has ended in a draw)

If the board is in an illegal state where both players appear to have completed a line, return the winner of the first matching line found when checking in this order: rows top-to-bottom, then columns left-to-right, then the main diagonal, then the anti-diagonal.

Constraints

  • board has exactly 9 elements.
  • Every element is 0, 1, or 2.
  • No other validation of board legality is required.

Examples

Example 1

Input: find_grid_winner([1, 1, 1, 0, 2, 0, 2, 0, 0])

Output: 1

Example 2

Input: find_grid_winner([1, 2, 0, 1, 2, 0, 0, 0, 0])

Output: 0

Hints

Hint 1

There are exactly 8 ways to win on a 3×3 grid. Write them all down as index triplets into the flat list before you write any logic.

Hint 2

For each triplet, a player owns that line if all three values are equal and at least one of them is non-zero. A line of three zeros must not count as a win.

Hint 3

Once you have the eight triplets, the solution body is a single loop: return the cell value on the first matching triplet, or return 0 after the loop exhausts all eight.