JSFiddle - React, Tailwind, and code Playground

Sudoku - check if sudoku is valid (no repeating numbers in each row and column and sector). Use hash table to pass over all elements only once (O(n) difficulty). Dynamic array creation

by Yurii Predborskyi

JavaScript

// sudoku validity check
/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
	let maps = {};
    for (let i = 0; i < board.length; i++) {
    	for (let j = 0; j < board[i].length; j++) {
      	if (board[i][j] === '.') continue;
        let sector = ('h' + Math.floor(i / 3)) + ('v' + Math.floor(j / 3));
        if (
        	(maps[sector] && maps[sector].includes(board[i][j])) ||
          (maps['row' + i] && maps['row' + i].includes(board[i][j])) ||
          (maps['col' + j] && maps['col' + j].includes(board[i][j]))
        ) {
        	return false;
        } else {
        	maps[sector] ? maps[sector].push(board[i][j]) : maps[sector] = [board[i][j]];
          maps['row' + i] ? maps['row' + i].push(board[i][j]) : maps['row' + i] = [board[i][j]];
          maps['col' + j] ? maps['col' + j].push(board[i][j]) : maps['col' + j] = [board[i][j]];
        }
      }
    }
    return true;
};

let sudoku = [
  [".","8","7","6","5","4","3","2","1"],
  ["2",".",".",".",".",".",".",".","."],
  ["3",".",".",".",".",".",".",".","."],
  ["4",".",".",".",".",".",".",".","."],
  ["5",".",".",".",".",".",".",".","."],
  ["6",".",".",".",".",".",".",".","."],
  ["7",".",".",".",".",".",".",".","."],
  ["8",".",".",".",".",".",".",".","."],
  ["9",".",".",".",".",".",".",".","."]
];

console.log('sudoku is ' + isValidSudoku(sudoku));