Skip to content

Instantly share code, notes, and snippets.

@BRonen
Last active March 23, 2025 20:49
Show Gist options
  • Save BRonen/e5ab1e5c7d3ddda78aafdb664ef7a7ae to your computer and use it in GitHub Desktop.
Save BRonen/e5ab1e5c7d3ddda78aafdb664ef7a7ae to your computer and use it in GitHub Desktop.
var isValidSudoku = function(board) {
const rows = new Array(9).fill(0).map(() => new Set());
const cols = new Array(9).fill(0).map(() => new Set());
const boxes = new Array(9).fill(0).map(() => new Set());
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const num = board[i][j];
if (num === '.') continue;
const boxIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3);
if (rows[i].has(num) || cols[j].has(num) || boxes[boxIndex].has(num)) return false;
rows[i].add(num);
cols[j].add(num);
boxes[boxIndex].add(num);
}
}
return true;
};
@BRonen
Copy link
Author

BRonen commented Mar 23, 2025

the execution time of this solution dropped to a third just by doing loop unrolling and inlining variables.

(from ~13ms to ~4ms average)

https://medium.com/@kallel.front/desafios-do-leetcode-e-a-busca-pela-performance-19c7c3fa1d6a

@BRonen
Copy link
Author

BRonen commented Mar 23, 2025

edit: new version using a code similar to the original one but using sets to hold the state, ended up using a couple more MBs of memory than the unrolled one but keeps the legibility of the original with a ~4ms average execution time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment