Several sets at once

Arrays and Hashing

Several sets at once

When one element belongs to more than one group, the difficulty is index arithmetic, not algorithms.

Key idea

One element, several constraints

Sometimes a single item has to satisfy more than one rule at once, and the rules cut across the data in different directions. A seat in a theatre belongs to a row and to a section. A cell in a grid belongs to a row, a column, and a block.

The move is always the same: keep one collection per constraint, and update all of them in the same pass. Writing a separate loop per constraint is the version that produces sixty lines and hides its bugs.

Here it is on a small grid, checking only two constraints: no repeated value in any row, and none in any column.

Gotcha

Skipping the blanks is not optional

Without the continue, the second blank in any row registers as a repeat of the first and the function rejects everything. It is one easy line to leave out, and the symptom, nothing is ever valid, does not point at it.

Why it works

Naming a region with integer division

The interesting constraint is usually the third kind: a block, tile, or bucket that a coordinate falls into. Integer division is what turns a coordinate into a region name.

For blocks of size b, the cell at (r, c) sits in block (r // b, c // b). With b = 3, rows 0, 1, 2 collapse to block row 0, rows 3, 4, 5 to block row 1, and so on.

Tip

Keep the region key as a tuple

You could flatten (r // 3, c // 3) into a single number with (r // 3) * 3 + c // 3. Both work. The tuple is harder to get wrong and reads better, and you are already comfortable with tuples as dict keys from the grouping lesson.

Tip

Complexity on a fixed board

When a grid has fixed dimensions the whole scan is technically O(1), since the work does not grow with anything. The more useful answer is O(n squared) for an n by n grid, then noting that n is fixed here. Saying both is the strongest version.

Where this returns

The same idea powers n-queens in Unit 10, where each queen constrains a column and two diagonals at once, and the diagonal names come from exactly this kind of index arithmetic. Get comfortable with it here, on a problem where the only difficulty is the bookkeeping.

Which cells share a block?

Using the block index (r // 3, c // 3), which of these pairs of cells sit in the same 3 by 3 block?

Valid Sudoku

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

Loading the workspace…
← Previous