Why it works
- Each row, column and box keeps a set of the digits already in it. A set answers "is this digit here?" at once, so a digit is checked against all three without looking over the board again.
- The box comes from the row and the column: r / 3 and c / 3 rounded down give the box row and the box column, 0 to 2, and (r / 3) × 3 + c / 3 numbers the boxes 0 to 8, row by row.
- One pass is enough: a repeat is caught when its second copy comes up, because the first one is already in the set. Empty cells take no part.
Complexity
Time O(1): the board is always 81 cells, and each digit is looked up in three sets once; for an n × n board it would be O(n²). Memory O(1) for the same reason: 27 sets of at most 9 digits.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗