Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a number is already in the given row.
DSA Javascript
function isInRow(board, row, num) {
for (let col = 0; col < 9; col++) {
if (board[row][col] === [1]) {
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable instead of the number to check.
✗ Incorrect
We check if the current cell in the row equals the number we want to place.
2fill in blank
mediumComplete the code to check if a number is already in the given column.
DSA Javascript
function isInCol(board, col, num) {
for (let row = 0; row < 9; row++) {
if (board[row][col] === [1]) {
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable instead of the number to check.
✗ Incorrect
We check if the current cell in the column equals the number we want to place.
3fill in blank
hardFix the error in checking if a number is in the 3x3 box.
DSA Javascript
function isInBox(board, startRow, startCol, num) {
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
if (board[startRow + row][startCol + col] === [1]) {
return true;
}
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with wrong variables like startRow or startCol.
✗ Incorrect
We compare each cell in the 3x3 box with the number to check if it is already present.
4fill in blank
hardFill both blanks to check if placing a number is valid in the Sudoku board.
DSA Javascript
function isValid(board, row, col, num) {
return !isInRow(board, row, num) && !isInCol(board, col, num) && !isInBox(board, row - row % 3, col - col % 3, [1]) && board[row][col] === [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined instead of 0 for empty cells.
✗ Incorrect
We check the number for the box and ensure the cell is empty (0) before placing.
5fill in blank
hardFill all three blanks to complete the backtracking solver function.
DSA Javascript
function solveSudoku(board) {
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (board[row][col] === [1]) {
for (let num = 1; num <= 9; num++) {
if (isValid(board, row, col, num)) {
board[row][col] = [2];
if (solveSudoku(board)) {
return true;
} else {
board[row][col] = [3];
}
}
}
return false;
}
}
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using null instead of 0 for empty cells.
Not resetting the cell on backtrack.
✗ Incorrect
We find empty cells (0), try numbers (num), place them, and backtrack by resetting to 0 if needed.
