Skip to main content

LeetCode Problem #794. Valid Tic-Tac-Toe State

Problem Statement:
Validate whether given three set of combination leads to valid Tic-Tac-Toe  pattern or not.
Given strings consists of 'x', 'o' or ' '.
Assume that game starts from 'x'. So, first players1 puts 'x' in the game then player2 takes the turn and inserts 'o'. The game will continue until one of the players win.

Our task is to find out whether given pattern is possible at any point of time of play. Return true if the given pattern is possible else return false.

Example 1:
Input:
['XXX', '   ', 'OOO']
Output:
 false

Explanation:
The given pattern is not possible because once the player 1 put three X in a row which is in the first row game is over, player 2 doesn't get a chance to put thrid O. So, this pattern is not possible.


Example 2:
Input:
['XOX', 'OOX ', 'XO ']
Output:
 true

Explanation:
The given pattern is possible.

Example 3:
Input:
['OXX', 'XOX', 'OXO']
Output:
 false

Explanation:
The given pattern is not possible because once the player 2 inserts O in diagonal manner, there is no chance for player one to insert one more X


Example 4:
Input:
['   ', '   ', '   ']
Output:
 true

Explanation:
This is the first step in the game where players start.

Approach to the Solution:
  1. To solve this problem one of the easy way would be to eliminate all the wrong possibilities.
  2. Here are the list of wrong possibilities:
    • Number of O is greater than number of X
    • Number of X is greater than number of O + 1
    • Games continue even after someone win.
  3. So, the solution would be: First count the number of X and number of O
  4. Compare the X and O as per the above conditions if any one of them is true return false as such pattern is not possible.
  5. Then find out whether game is completed by any player or not. If game is completed them save who won the game.
  6. Whether game is completed or not can be checked by comparing rows and columns


Solution in C++:
class Solution {
public:
    bool validTicTacToe(vector<string>& board) {
        int x = GetCharCount(board, 'X');
        int o = GetCharCount(board, 'O');
       
        if(x < o || x > o + 1)
            return false;
        bool is_o_bingo = false;
        if(IsBingo(board, is_o_bingo)){
            if((is_o_bingo && x != o)  || (!is_o_bingo && x == o))
            return false;
        }
        return true;
    }
   
private:
    bool IsBingo(vector<string> board, bool &is_o_bingo){
        //top row middle
        if(board[0][0] != ' ' && board[0][0] == board[0][1] && board[0][0] == board[0][2]){
            if(board[0][0] == 'O')
                is_o_bingo = true;
            return true;
        }
        // left column middle
        else if(board[0][0] != ' ' && board[0][0] == board[1][0] && board[0][0] == board[2][0]){
            if(board[0][0] == 'O')
                is_o_bingo = true;
            return true;
        }
        // bottom row middle
        else if(board[2][0] != ' ' && board[2][0] == board[2][1] && board[2][0] == board[2][2]){
            if(board[2][0] == 'O')
                is_o_bingo = true;
            return true;
        }
        // right column middle
        else if(board[0][2] != ' ' && board[0][2] == board[1][2] && board[0][2] == board[2][2]){
            if(board[0][2] == 'O')
                is_o_bingo = true;
            return true;
        }
        // middle column
        else if(board[1][1] != ' ' && board[1][1] == board[0][1] && board[1][1] == board[2][1]){
            if(board[1][1] == 'O')
                is_o_bingo = true;
            return true;
        }
        // middle row
        else if(board[1][1] != ' ' && board[1][1] == board[1][0] && board[1][1] == board[1][2]){
            if(board[1][1] == 'O')
                is_o_bingo = true;
            return true;
        }
        //diagonal elements
        else if(board[1][1] != ' ' && board[1][1] == board[0][0] && board[1][1] == board[2][2]){
            if(board[1][1] == 'O')
                is_o_bingo = true;
            return true;
        }
        //another diagonal
        else if(board[1][1] != ' ' && board[1][1] == board[2][0] && board[1][1] == board[0][2]){
            if(board[1][1] == 'O')
                is_o_bingo = true;
            return true;
        }
        return false;
    }
    int GetCharCount(vector<string> board, char c){
            int count = 0;
        for(int iter = 0; iter < board.size(); ++iter){
            for(int i = 0; i < board[iter].length(); ++i){
                if(board[iter][i] == c)
                    ++count;
            }
        }
        return count;
    }
};


Comments

Popular posts from this blog

Leet Code: Problem #710 Random Pick with Blacklist

Given a blacklist  B containing unique integers from [0, N) , write a function to return a uniform random integer from [0, N) which is NOT  in B . Optimize it such that it minimizes the call to system’s Math.random() . Note: 1 <= N <= 1000000000 0 <= B.length < min(100000, N) [0, N)  does NOT include N. See interval notation . Example 1: Input: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] Output: [null,0,0,0] Example 2: Input: ["Solution","pick","pick","pick"] [[2,[]],[],[],[]] Output: [null,1,1,1] Example 3: Input: ["Solution","pick","pick","pick"] [[3,[1]],[],[],[]] Output: [null,0,0,2] Example 4: Input: ["Solution","pick","pick","pick"] [[4,[2]],[],[],[]] Output: [null,1,3,1] Explanation of Input Syntax: The input is two lists: the subroutines called and their argume...

Creating Self Signed SSL Certificates for HTTPS Communication

Self Signed CA: Create Private Key for Self Signed CA openssl ecparam -genkey -name secp256r1 | openssl ec -out ca.key     Create CA Certificate for Self Signed CA openssl req -new -x509 -days 36500 -key ca.key -out ca.pem -subj "/C=IN/ST=Karnataka/L=Bengaluru/O=company name/OU=Prod Operations Department/CN=prodops .domain.com   Verify the content of CA certificate openssl x509 -in ca.pem -noout -text Client CERTIFICATE: CLIENT_ID="<Client-Product>" e.g. CLIENT_ID="ClientID" CLIENT_SERIAL="<Client-Release-Number>" e.g. CLIENT_SERIAL="6889" Create Private Key for Client openssl ecparam -genkey -name secp256r1 | openssl ec -out  ${CLIENT_ID}_${CLIENT_SERIAL}.key                   Generate the Certificate Signing Request CSR openssl req -new -key ${CLIENT_ID}_${CLIENT_SERIAL}.key -out ${CLIENT_ID}_${CLIENT_SERIAL}.csr -subj "/C=IN/ST=Karnataka/L=Bengalur...

Tree Data Structure related must solve programming questions: Part - 1

LeetCode Problem #687 Given a binary tree find the longest possible path with same node values. The length of the path is determined the number of edges between the node. Example 1: Input: 5 / \ 4 5 / \ \ 1 1 5 Output:  2   Example 2: Input: 1 / \ 4 5 / \ \ 4 4 5 Output:  2 Solution in C++: /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution ...