{"id":884,"date":"2023-12-10T16:48:53","date_gmt":"2023-12-10T16:48:53","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=884"},"modified":"2023-12-11T08:40:18","modified_gmt":"2023-12-11T08:40:18","slug":"valid-sudoku","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/valid-sudoku\/","title":{"rendered":"Check if a Sudoku is Valid or Not (C++, Java, Python)"},"content":{"rendered":"\n<p>We know that Sudoku is a popular puzzle game that requires players to fill a 9&#215;9 grid with numbers from 1 to 9. This article will discuss an approach, along with examples, to solve this interesting leetcode problem called &#8216;Valid Sudoku&#8217; to check if the sudoku board configuration is correct or not.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Valid Sudoku Problem?<\/strong><\/h2>\n\n\n\n<p><strong>In the Valid Sodoku problem, we are given a 9&#215;9 sudoku board, our goal is to check whether it is valid or not.<\/strong> The objective is to ensure that each row, column, and 3&#215;3 sub-grid contains all the digits from 1 to 9 without repetition. <\/p>\n\n\n\n<p>A valid sudoku must follow the 3 following conditions:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Each row must contain the digits 1 to 9 without repetition.<\/li>\n\n\n\n<li>Each column must contain the digits 1 to 9 without repetition.<\/li>\n\n\n\n<li>Each 3&#215;3 sub-grid must contain the digits 1 to 9 without repetition.<\/li>\n<\/ol>\n\n\n\n<p>We have to consider only the filled value in the grid to check the validity.<\/p>\n\n\n\n<p>Let us understand it with an example with this board:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"560\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1-1024x560.png\" alt=\"Example of sudoku board\" class=\"wp-image-896\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1-1024x560.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1-300x164.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1-768x420.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1-750x410.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1-1140x623.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/Untitled-2023-11-07-1458-1.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Here are 9 subgrids of 3&#215;3.<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Output = valid&nbsp;<\/code><\/pre>\n\n\n\n<p>Because there is no repetition within rows, columns, and subgrids<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>HashSet to Check Sudoku Configuration is Valid<\/strong><\/h2>\n\n\n\n<p>To solve this problem, we will use a HashSet to check the repetition of numbers within rows, columns, and subgrids.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"400\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7-1024x400.png\" alt=\"subgrid example\" class=\"wp-image-897\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7-1024x400.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7-300x117.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7-768x300.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7-750x293.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7-1140x445.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-7.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>We will declare a HashSet of strings to keep track of elements seen during the iteration<\/li>\n\n\n\n<li>We will run a nested loop and check only for nonempty cells using this condition board[i][j] != &#8216; &#8216;\n<ul class=\"wp-block-list\">\n<li>We will make a string like for row string is \u201crow+i+board[i][j]\u201d (here i is row number), for columns \u201ccol+j+board[i][j]\u201d (here j is column number), for box, we will use a formula to obtain box number (i\/3)*3+(j\/3) and string for the box is \u201cbox+(i\/3)*3+(j\/3)+board[i][j]<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"400\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8-1024x400.png\" alt=\"sudoku board dry run\" class=\"wp-image-898\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8-1024x400.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8-300x117.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8-768x300.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8-750x293.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8-1140x445.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-8.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>&nbsp;Now we will check if the string of row, column, and box is present in the set then will return false otherwise we will return true. If all iterations run successfully.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Below is the C++ program to solve the Valid Sudoku problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nclass Solution {\npublic:\n    bool isValidSudoku(vector&lt;vector&lt;char&gt;&gt;&amp; board) {\n        unordered_set&lt;string&gt; seen;\n        for (int i = 0; i &lt; 9; i++) {\n            for (int j = 0; j &lt; 9; j++) {\n                if (board[i][j] != '.') {\n                    if (!seen.insert(&quot;row&quot; + to_string(i) + board[i][j]).second ||\n                        !seen.insert(&quot;col&quot; + to_string(j) + board[i][j]).second ||\n                        !seen.insert(&quot;box&quot; + to_string((i \/ 3) * 3 + j \/ 3) + board[i][j]).second) {\n                        return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n};\n\nint main() {\n    \/\/ Example usage:\n    Solution solution;\n vector&lt;vector&lt;char&gt;&gt; board = {\n    {'.', '2', '.', '4', '5', '6', '.', '8', '9'},\n    {'4', '.', '6', '7', '8', '9', '1', '.', '3'},\n    {'7', '8', '.', '1', '.', '3', '4', '5', '6'},\n    {'2', '3', '4', '5', '6', '.', '8', '9', '1'},\n    {'5', '6', '7', '8', '9', '1', '.', '3', '4'},\n    {'8', '.', '1', '2', '3', '4', '5', '6', '7'},\n    {'3', '4', '5', '6', '.', '8', '.', '1', '2'},\n    {'6', '7', '8', '9', '1', '.', '3', '.', '5'},\n    {'9', '1', '.', '3', '4', '5', '6', '7', '.'}\n};\n\n    bool result = solution.isValidSudoku(board);\n    cout &lt;&lt; (result ? &quot;Valid&quot; : &quot;Invalid&quot;) &lt;&lt; endl;\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>The implementation is quite similar in Java:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.HashSet;\n\nclass Solution {\n    public boolean isValidSudoku(char[][] board) {\n        HashSet&lt;String&gt; seen = new HashSet&lt;&gt;();\n        for (int i = 0; i &lt; 9; i++) {\n            for (int j = 0; j &lt; 9; j++) {\n                if (board[i][j] != '.') {\n                    if (!seen.add(&quot;row&quot; + i + board[i][j]) ||\n                        !seen.add(&quot;col&quot; + j + board[i][j]) ||\n                        !seen.add(&quot;box&quot; + (i \/ 3) * 3 + j \/ 3 + board[i][j])) {\n                        return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n\n    public static void main(String[] args) {\n        Solution solution = new Solution();\n        char[][] board = {\n            {'.', '2', '.', '4', '5', '6', '.', '8', '9'},\n            {'4', '.', '6', '7', '8', '9', '1', '.', '3'},\n            {'7', '8', '.', '1', '.', '3', '4', '5', '6'},\n            {'2', '3', '4', '5', '6', '.', '8', '9', '1'},\n            {'5', '6', '7', '8', '9', '1', '.', '3', '4'},\n            {'8', '.', '1', '2', '3', '4', '5', '6', '7'},\n            {'3', '4', '5', '6', '.', '8', '.', '1', '2'},\n            {'6', '7', '8', '9', '1', '.', '3', '.', '5'},\n            {'9', '1', '.', '3', '4', '5', '6', '7', '.'}\n        };\n\n        boolean result = solution.isValidSudoku(board);\n        System.out.println(result ? &quot;Valid&quot; : &quot;Invalid&quot;);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the Python program as well:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">from typing import List\n\nclass Solution:\n    def isValidSudoku(self, board: List[List[str]]) -&gt; bool:\n        seen = set()\n        for i in range(9):\n            for j in range(9):\n                if board[i][j] != '.':\n                    if f&quot;row{i}{board[i][j]}&quot; in seen or \\\n                       f&quot;col{j}{board[i][j]}&quot; in seen or \\\n                       f&quot;box{(i \/\/ 3) * 3 + j \/\/ 3}{board[i][j]}&quot; in seen:\n                        return False\n                    seen.add(f&quot;row{i}{board[i][j]}&quot;)\n                    seen.add(f&quot;col{j}{board[i][j]}&quot;)\n                    seen.add(f&quot;box{(i \/\/ 3) * 3 + j \/\/ 3}{board[i][j]}&quot;)\n        return True\n\n# Example usage\nsolution = Solution()\nboard = [\n    ['.', '2', '.', '4', '5', '6', '.', '8', '9'],\n    ['4', '.', '6', '7', '8', '9', '1', '.', '3'],\n    ['7', '8', '.', '1', '.', '3', '4', '5', '6'],\n    ['2', '3', '4', '5', '6', '.', '8', '9', '1'],\n    ['5', '6', '7', '8', '9', '1', '.', '3', '4'],\n    ['8', '.', '1', '2', '3', '4', '5', '6', '7'],\n    ['3', '4', '5', '6', '.', '8', '.', '1', '2'],\n    ['6', '7', '8', '9', '1', '.', '3', '.', '5'],\n    ['9', '1', '.', '3', '4', '5', '6', '7', '.']\n]\n\nresult = solution.isValidSudoku(board)\nprint(&quot;Valid&quot; if result else &quot;Invalid&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Valid<\/code><\/pre>\n\n\n\n<p>To know more about HashSet, we have a detailed <a href=\"https:\/\/favtutor.com\/blogs\/hashing-in-data-structure\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/blogs\/hashing-in-data-structure\">guide on Hashing<\/a> for beginners.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Complexity Analysis<\/strong><\/h3>\n\n\n\n<p>The time complexity of the algorithm is O(N^2), where N is the size of the Sudoku board (N x N) as the algorithm traverses through each cell in the board exactly once, resulting in a nested loop structure iterating over N x N cells.<\/p>\n\n\n\n<p>The space complexity of the algorithm is O(N) due to the usage of additional space for storing sets.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h3>\n\n\n\n<p>In conclusion, the &#8220;valid sudoku&#8221; <a href=\"https:\/\/leetcode.com\/problems\/valid-sudoku\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/leetcode.com\/problems\/valid-sudoku\/\" rel=\"noreferrer noopener nofollow\">leetcode problem<\/a> is used to find whether the order of numbers present in the sudoku board is valid or not. It can be efficiently solved using the HashSet.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will solve the valid sudoku leetcode problem using HashSet approach, along with implementation in C++, Java and Python.<\/p>\n","protected":false},"author":12,"featured_media":891,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[15],"class_list":["post-884","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/884","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=884"}],"version-history":[{"count":5,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/884\/revisions"}],"predecessor-version":[{"id":922,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/884\/revisions\/922"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/891"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=884"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=884"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=884"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}