Customer Support: firstname.lastname@example.org
We are listening to your every feedback,
and taking action to constantly improve your learning experience.
If you have any feedback, please use this form:
Given a Sudoku, design an algorithm to solve it.
A sudoku solution must satisfy all of the following rules:
- Each of the digits 1-9 must occur exactly once in each row.
- Each of the digits 1-9 must occur exactly once in each column.
- Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
The '0' character indicates empty cells.
Solution:This is one of my personal favorites. Solving this problem shows the power and advantage of knowing the basic algorithms really good.
If someone is asked to design an algorithm with working code in a 40 mins coding interview, it might seem daunting. But here we would see how if you understand how backtracking works you would be able to come up with a very simple yet elegant algorithm with working code in under 30 minutes.
The concept is simple: we do an exhaustive search. For every cell that does not contain '.' we compute what are the values that cell can contain, and for each and every valid candidate we recursively call backtrack(...) to see if we can get a valid solution. Once we get the first valid solution the process stops.
We will be using our backtracking template discussed in Backtracking Fundamentals to write our code.
Code:I have put all the implementaion details and in-depth algorithmic discussion in the inline comments in the code below:
This is a Premium Content.
Please subscribe to Low Level Design course to access the content.
The above content is written by:
If you have any feedback, please use this form: https://thealgorists.com/Feedback.
Follow Us On LinkedIn