Leetcode 794: Valid Tic-Tac-Toe State

grid47
grid47
Exploring patterns and algorithms
Aug 19, 2024 9 min read

A Tic-Tac-Toe board where valid states are checked, with valid states softly glowing as they’re found.
Solution to LeetCode 794: Valid Tic-Tac-Toe State Problem

Given a Tic-Tac-Toe board represented as a 3x3 string array, return true if and only if this board could have been reached during a valid Tic-Tac-Toe game. In a valid game, players alternate placing ‘X’ and ‘O’ characters into empty spaces. ‘X’ always goes first, and no player can move after the game has ended.
Problem
Approach
Steps
Complexity
Input: The input is a 3x3 Tic-Tac-Toe board represented as a string array where each element in the array is a string of length 3.
Example: board = ['XOX', ' O ', ' ']
Constraints:
• board.length == 3
• board[i].length == 3
• board[i][j] is either 'X', 'O', or ' ' (empty space).
Output: Return a boolean value indicating whether the given board configuration could be reached during a valid game.
Example: Output: true
Constraints:
• The output should be either true or false.
Goal: The goal is to determine if the given Tic-Tac-Toe board is a valid position during a game, respecting the rules of turn order and winning conditions.
Steps:
• Count the number of 'X' and 'O' characters on the board.
• Check if a player has won. A player wins if they have three of their symbols in a row, column, or diagonal.
• Ensure that the number of 'X's is either equal to or one more than the number of 'O's.
• If a player has won, check that the game is consistent with turn order (i.e., 'X' should not have won before 'O' had a chance to play).
Goal: Ensure that the board adheres to the rules of Tic-Tac-Toe, considering the turn order and winning conditions.
Steps:
• The board must be a 3x3 grid.
• The characters on the board are restricted to 'X', 'O', or ' '.
• The number of 'X' can only be equal to or one more than the number of 'O'.
Assumptions:
• The board is a 3x3 grid.
• Players alternate placing 'X' and 'O' with 'X' going first.
• No more moves can be made after the game has ended.
Input: Input: board = ['XOX', ' O ', ' ']
Explanation: This board configuration is invalid because 'O' should not have played after 'X' placed their 'X'. 'X' should always play first.

Input: Input: board = ['XOX', ' X ', ' ']
Explanation: This board configuration is valid because the count of 'X' is one more than the count of 'O', and no one has won yet.

Input: Input: board = ['XOX', 'O O', 'XOX']
Explanation: This board configuration is valid because the game ended with no inconsistencies between turn order and the game status.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus