Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)

Back To Back SWE · Beginner ·⚡ Algorithms & Data Structures ·7y ago

Key Takeaways

The video demonstrates how to implement a Sudoku solver using the backtracking algorithm, a classic systems design problem, with a focus on recursion and constraint satisfaction. It covers the basics of Sudoku, the backtracking approach, and how to generalize the solution to an N by N board, recognizing it as an NP-complete problem.

Full Transcript

so today we're gonna look at a problem that is on the caliber of n queens in terms of backtracking this is the Sudoku solver problem so basically you're given a Sudoku puzzle and you need to create an algorithm that solves that puzzle we are going to make this problem fantastically simple in this video because once you know the keys to solving it it becomes very easy to implement it's fine you can come through ok so we're going to apply the same keys the three keys to backtracking and we're going to create a recursive algorithm that solves each cell going through so after this video will you be a better person probably not well you know how to solve a Sudoku puzzle I'm pretty sure you will so let's get into it all right so I've noticed in the past few videos that I have been pretty loud and like yelling I don't know I get kind of excited doing these but I'm gonna take a little tone down approach to this one implement a Sudoku solver this question follows the same pattern as her previous backtracking problems we're going to make a choice we're going to have constraints on that choice and we're going to have a goal that we want to reach at the end here's a pseudo keyboard let's first look at the constraints and the rules on this problem we want to have only the numbers 139 in every row every column and every sub grid you can see there's nine sub grades here we have a nine by nine board and we're going to have three sub grids and each of these rows so there's a subject there's one there's one you can you see what I mean so the key is whenever we're doing problems like this there's many ways to approach them but we notice with this problem that we are told to make choices and find a globally correct answer so this probably entails backtracking but we're going to look at both approaches to this problem the brute force as well as the backtracking approach and see how they differ so our first approach to this question is going to be a brute-force approach so the brute force goes like this we're going to generate every single possible board of Sudoku it's not going to be a valid pseudo board just every possible board that we could generate from a nine given this we would try to place a one-year numbers one through nine here numbers one through nine here 1 through 9 1 through 9 1 through 9 we would generate every single possible board and then once we have all the possible boards that we could have gotten from the certain issue arrangement then we validate each of those boards we validate each of the exponential amounts of full boards that we get at the end so generate all boards validate all of those exponential boards exponential amount of boards the problem is that in a well-formed sodoku board there's going to only be one solution so we are going to be generating and exponential amounts of boards we are not going to direct our recursion we're just going to generate all the possible boards it can literally be a board of just all fives all these empty spaces get fives and then we're going to see whether that is a valid sodoku board and we're only going to choose one of that exponential amount it's wasting a lot of time and that's not the approach you want to go so what we want to do is we want to direct our recursion and we want to use backtracking for this problem so now we get to the three keys to backtracking to solve this problem the three key things we need to understand when we solve this first of all we need to be cognizant of our choice every time we see a cell with a number we can't do anything with that it already has a number whenever we see an empty cell then that is our chance to take action and and place a number what numbers can we place we can place a number 1 through 9 in an empty cell that is our decision space every single cell is going to have a basically a recursive call that has the potentiality to place 1 through 9 so whenever used this cell I say hey let me place 139 when I reached this cell I say I can place 1 through 9 and then i recurse on that decision we choose a number recurse on the decision we are going to traverse the board in a fashion like this we're going to go row by row and we're going to solve each column in the row when we finish a row we're going to advance to the next row and we're going to set the column back to zero solve column zero all the way up to the length minus one and then we know we're done and then we go down here to the next row and reset our column that is our choice in the empty spaces we're going to place one through nine so our constraints our placements cannot break the board so if I place a 5 there that means we broke in our constraints do you see here in the road there is a 5 right there so we cannot do that our constraints are when we place an item it cannot break the board when we place an item it can't break the board what we do is when we place an item before we even place it we see will this item break the pseudo whoo properties we would not even place 5 there because we know it would break it but how do we know are we going to do it N squared time check and check the whole board check whether the whole board is invalid no and here's the reason why every single decision we make up to the point of this placement whether we're here or whether we're all the way down here every decision ensured that that placement would be a valid board we do not place an item if it breaks the board so if I place a 1 here and then I have to make a placement in the next cell I know every placement before what I'm doing right now did not break the board so what does that mean that means the placement right there the placement I'm doing all I need to see is does it break the row it's sitting in does it break the column it's sitting in and does it break the sub grid it is sitting and these are our constraints so right here all I need to know is can I place a 1 here no I can't there's a 1 here and there's a 1 in the call can I place a 2 here there's no 2 and in the column there's no two in the row and there's no 2 in the sub grid so I can place the two less place too and so now I come to this cell this cell already has a number I skip it and now I come to this cell and you see what I'm getting at we tried placements in each cell going in a fashion where we traverse the board like this and go finish a row go to the next row finish that row goes next row finish that row go to the next row and what we do is we ensure that the placement we are placing is not going to break the board and what will happen is when I'm at the tap placement I know every single placement performing has not broken the board and therefore I only need to check the row column and sub grid finally what is our goal our goal is to fill the whole board we want to fill every empty space in this board how do I know I am finished when I finished the last row and I go to the next row if I am out of balance on the number of rows if my thorough number on working on equals the number of rows I am an indexed one out of bounds and then I know I have finished every row remember in programming we index off a zero not one so now that we have the three keys to recursion we know how to approach this problem and we can build a recursive function that one makes a choice on every empty cell trying numbers one through nine before we place an item and do our recursion on it we are going to see if it breaks our Sudoku properties if it does not break our properties we place the item advance to the next column if we finish a row we're going to advance to the next row and then go to column zero that is our base case and again the code is in the description if you want to see this I've commented every line it is so crystal clear and it will make sense when you read it so now let's get on to the space and time complexity to this problem so if you want to see the full solution to this problem the code is in the description commented fully has passed test cases only code you can throw it in there and try it yourself so that you can get a deep understanding on this problem I highly encourage you to check the code out as well as this explanation so for the time and space complexities to this problem it is kind of it doesn't really make much sense to really discuss time complexities because sodoku boards is traditionally our nine by nine so we can't really scale the size of our input Big O is all about tail behavior and scaling input and pounding on the time and space it would take for our algorithms are up but Sudoku can be generalized to an N by n board and it is a np-complete problem when you generalize the Sudoku problem to it and by n board and therefore we know that at least it is going to be an exponential if not super exponential time complexity so you can do more research on this but definitely in an interview you're probably not going to need to do any proofs or know the rigorous balance only time and space for something this rigorous and difficult this would be difficult to pull off an interview code wise at least until you can find the time in space it would be even harder to understand the amount of force we can make from every decision point and put a bound on the time complexity of that algorithm and how it runs that's all for this video again check the code in the description fully commented it is actually a lot of code that's why I'm not walking through it here I really wish I could walk through it but it would take me like half an hour to an hour to write everything thank you for watching I hope you understand this question better if you like videos like this hit the like button subscribe to the channel I'm trying to cover as many questions I can I want everyone who watches is to have a deep understanding of these concepts and questions and not feel lost when you're answering them because all it takes is understanding the intuition and then you can tackle different questions that you've probably never seen before [Music]

Original Description

Free 5-Day Mini-Course: https://backtobackswe.com Try Our Full Platform: https://backtobackswe.com/pricing 📹 Intuitive Video Explanations 🏃 Run Code As You Learn 💾 Save Progress ❓New Unseen Questions 🔎 Get All Solutions Question: Implement a Sudoku solver. (a classic Sudoku board is 9x9) The Rules of Sudoku: We are working with numbers 1 thorugh 9. Each number can only appear once in a: Row Column And one of the 3 x 3 subboxes Approach 1 (Brute Force) Try every possible assignment to empty entries and then at the end validate if the sudoku board is valid or not. With no constraints, given a 9x9 board we have at max 81 spaces where in each space we can place the number 1-9 (but on a normal board many spaces will already have a number before we even start solving) This means that there are 9^81 total arrangements of the board (as a loose upper bound). This is 1.9662705 * 10 ^ 77 boards just for a 9 x 9 board. This would take too long. Approach 2 (Apply The Constraints) The backtracking approach. We can traverse and place an entry in empty cells one by one. We then check the whole board to see if it is still valid. If it is we continue our recursion. If it is not we do not even follow that path. When all entries have been filled, we are finished. The 3 Keys To Backtracking: Our Choice What we place in an empty cell that we see. Our Constraints Standard Sudoku constraints. We cannot make a placement that will break the board. Our Goal Place all empty spaces on the board. We will know we have done this when we have placed a valid value in the last cell in our search which programmatically will be the bottom right cell in the 2D matrix. Validating Placements Before We Place Them INSIGHT: We could traverse every row, column, and 3x3 subgrid to perform validation but at every decision point we know that we are adding onto a grid that is already valid. So we just check the row, column, and subgrid of the item that has been added.
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Back To Back SWE · Back To Back SWE · 20 of 60

1 4 Tips To Learn Java Programming As Fast As Possible As A Beginner
4 Tips To Learn Java Programming As Fast As Possible As A Beginner
Back To Back SWE
2 3 Mistakes Beginners Make When First Learning Java and Android Development
3 Mistakes Beginners Make When First Learning Java and Android Development
Back To Back SWE
3 How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
Back To Back SWE
4 The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
Back To Back SWE
5 Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Back To Back SWE
6 The N Queens Problem using Backtracking/Recursion - Explained
The N Queens Problem using Backtracking/Recursion - Explained
Back To Back SWE
7 Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Back To Back SWE
8 How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
Back To Back SWE
9 Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Back To Back SWE
10 The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
Back To Back SWE
11 The Dutch National Flag Problem (The Quicksort "Band-Aid")
The Dutch National Flag Problem (The Quicksort "Band-Aid")
Back To Back SWE
12 Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Back To Back SWE
13 The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
Back To Back SWE
14 How To Permute A String - Generate All Permutations Of A String
How To Permute A String - Generate All Permutations Of A String
Back To Back SWE
15 The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
Back To Back SWE
16 Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search -  First Occurrence Of Substring
Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search - First Occurrence Of Substring
Back To Back SWE
17 Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Back To Back SWE
18 Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Back To Back SWE
19 Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Back To Back SWE
Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Back To Back SWE
21 Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Back To Back SWE
22 Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Back To Back SWE
23 Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Back To Back SWE
24 Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Back To Back SWE
25 The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
Back To Back SWE
26 Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Back To Back SWE
27 Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Back To Back SWE
28 Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Back To Back SWE
29 Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Back To Back SWE
30 The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
Back To Back SWE
31 Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Back To Back SWE
32 Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Back To Back SWE
33 Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Back To Back SWE
34 Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Back To Back SWE
35 Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Back To Back SWE
36 Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Back To Back SWE
37 Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Back To Back SWE
38 Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Back To Back SWE
39 Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Back To Back SWE
40 Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Back To Back SWE
41 Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Back To Back SWE
42 Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Back To Back SWE
43 What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
Back To Back SWE
44 An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
Back To Back SWE
45 Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Back To Back SWE
46 A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
Back To Back SWE
47 Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Back To Back SWE
48 Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Back To Back SWE
49 All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
Back To Back SWE
50 Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Back To Back SWE
51 Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Back To Back SWE
52 Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Back To Back SWE
53 Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Back To Back SWE
54 Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Back To Back SWE
55 The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
Back To Back SWE
56 Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Back To Back SWE
57 Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Back To Back SWE
58 The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
Back To Back SWE
59 Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Back To Back SWE
60 Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Back To Back SWE

This video teaches how to implement a Sudoku solver using the backtracking algorithm, covering the basics of Sudoku, the backtracking approach, and how to generalize the solution to an N by N board. It provides a comprehensive understanding of systems design and recursion. By following the steps outlined in the video, viewers can design and implement their own Sudoku solver.

Key Takeaways
  1. Generate all possible boards
  2. Validate each board
  3. Place a number 1-9 in an empty cell
  4. Use backtracking to direct recursion
  5. Try numbers 1-9 in an empty cell
  6. Check if a number breaks Sudoku properties by checking row, column, and sub-grid
  7. Place a number if it does not break Sudoku properties
  8. Advance to the next column
  9. Finish a row and advance to the next row
  10. Build a recursive function
💡 The backtracking algorithm is a powerful tool for solving complex problems like Sudoku, and understanding how to apply it can help viewers tackle similar systems design challenges.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →