Back to challenges
Medium 0 solved 0% acceptance

Tic-Tac-Toe Winner

Decide the result of a tic-tac-toe board.

What you'll learn

  • Check rows, columns and diagonals
  • Detect a draw or an unfinished game
  • Keep grid checks readable

Problem

A 3×3 board is given as three strings of X, O and . (empty). A player wins with three of their marks in a row, column or diagonal. Boards never have two winners.

Implement tic_tac_toe_winner(board).

Input

board: Three rows of three characters each.

Output

Return "X" or "O" for the winner, "Draw" if the board is full with no winner, or "Pending" if empty cells remain and nobody has won.

Constraints

board has exactly 3 rows of length 3

Examples

Example 1
Input:
board = ["XOX", ".X.", "O.X"]

Expected output:
expected = "X"
Input:
std::vector<std::string> board = {"XOX", ".X.", "O.X"};

Expected output:
std::string expected = "X";
Input:
string[] board = new string[] {"XOX", ".X.", "O.X"};

Expected output:
string expected = "X";

Explanation

X holds the diagonal from top-left to bottom-right, so X wins.

Example 2
Input:
board = ["XOX", "XOO", "OXX"]

Expected output:
expected = "Draw"
Input:
std::vector<std::string> board = {"XOX", "XOO", "OXX"};

Expected output:
std::string expected = "Draw";
Input:
string[] board = new string[] {"XOX", "XOO", "OXX"};

Expected output:
string expected = "Draw";

Explanation

The board is full and no line has three of a kind: Draw.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Check every row, column, and the two diagonals for three identical non-empty marks.

Hint 2

Track whether any empty cells remain while scanning the board once.

Hint 3

Remember that a full board with no winner is a draw, otherwise it is pending.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.