Arrays and Hashing
12 / 170Arrays and HashingLesson 7 of 10About 35 min
When one element belongs to more than one group, the difficulty is index arithmetic, not algorithms.
Here it is on a small grid, checking only two constraints: no repeated value in any row, and none in any column.
from collections import defaultdict def rows_and_cols_ok(grid): rows = defaultdict(set) cols = defaultdict(set) for r in range(len(grid)): for c in range(len(grid[r])): value = grid[r][c] if value == ".": continue # blanks are not a constraint if value in rows[r] or value in cols[c]: return False rows[r].add(value) cols[c].add(value) return True print(rows_and_cols_ok([["1", "2"], ["2", "1"]]))print(rows_and_cols_ok([["1", "2"], ["1", "."]]))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.
Using the block index (r // 3, c // 3), which of these pairs of cells sit in the same 3 by 3 block?
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.