Sudoku
Code Golf
Programming Challenge
Puzzle Solver
Grid Validation

Code Golf Validate Sudoku Grid

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Sudoku validation is a common coding challenge and a frequent code golf target. Golfed solutions optimize for character count, but production-quality understanding still requires clear validation rules. A valid 9 by 9 Sudoku grid must contain digits 1 through 9 exactly once in every row, column, and 3 by 3 block.

Validation Rules in Concrete Form

Given a completed grid:

  • Each row set must equal the digits 1 to 9.
  • Each column set must equal the digits 1 to 9.
  • Each 3 by 3 subgrid set must equal the digits 1 to 9.

For challenge variants allowing blanks, adjust rules to ignore zeros or dots as needed. Always define whether input is complete puzzle or partial puzzle.

Readable Validator First

Before golfing, write a clean implementation for correctness.

python
1def valid_group(nums):
2    return sorted(nums) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
3
4
5def validate_sudoku(grid):
6    # rows
7    for r in range(9):
8        if not valid_group(grid[r]):
9            return False
10
11    # columns
12    for c in range(9):
13        col = [grid[r][c] for r in range(9)]
14        if not valid_group(col):
15            return False
16
17    # 3 by 3 blocks
18    for br in range(0, 9, 3):
19        for bc in range(0, 9, 3):
20            block = []
21            for r in range(br, br + 3):
22                for c in range(bc, bc + 3):
23                    block.append(grid[r][c])
24            if not valid_group(block):
25                return False
26
27    return True

This version is easy to test and reason about.

Compact Golf-Friendly Approach

Code golf prefers expression compression. A common strategy is to generate all 27 groups and test uniqueness with sets.

python
1def golfish_valid(g):
2    groups = []
3    groups += g
4    groups += [[g[r][c] for r in range(9)] for c in range(9)]
5    groups += [[g[r+i][c+j] for i in range(3) for j in range(3)]
6               for r in (0, 3, 6) for c in (0, 3, 6)]
7    return all(set(x) == set(range(1, 10)) for x in groups)

This is not minimal byte count, but it demonstrates the same compression idea used in golf solutions.

Input Normalization for Real Submissions

Challenge inputs vary:

  • Nested lists of ints.
  • String rows.
  • Flat 81-character string.

Normalize early so validation logic stays stable.

python
1def parse_flat_string(s):
2    if len(s) != 81 or any(ch not in "123456789" for ch in s):
3        raise ValueError("input must be 81 digits 1-9")
4    nums = [int(ch) for ch in s]
5    return [nums[i:i+9] for i in range(0, 81, 9)]

In code golf you may skip robust checks, but in general-purpose code validation of shape and symbols matters.

Performance Considerations

For a standard 9 by 9 grid, runtime differences are negligible. Even straightforward implementations complete instantly. In challenge settings, byte count matters more than asymptotic complexity.

If generalized to larger Sudoku variants, bitmask approaches become attractive, but that is usually outside standard puzzle constraints.

Common Golf Tradeoffs

Golfed code often sacrifices:

  • Readability.
  • Error handling.
  • Input diagnostics.
  • Maintainability.

That tradeoff is acceptable in code golf competition, but not in production systems where clear debugging and user feedback are required.

A practical compromise is to keep two versions:

  • A clean tested implementation.
  • A golfed version for challenge submission.

Test Case Examples

Use one known valid grid and one invalid grid with subtle duplicates.

python
1valid = [
2    [5,3,4,6,7,8,9,1,2],
3    [6,7,2,1,9,5,3,4,8],
4    [1,9,8,3,4,2,5,6,7],
5    [8,5,9,7,6,1,4,2,3],
6    [4,2,6,8,5,3,7,9,1],
7    [7,1,3,9,2,4,8,5,6],
8    [9,6,1,5,3,7,2,8,4],
9    [2,8,7,4,1,9,6,3,5],
10    [3,4,5,2,8,6,1,7,9],
11]
12
13invalid = [row[:] for row in valid]
14invalid[0][0] = 6
15
16print(validate_sudoku(valid))
17print(validate_sudoku(invalid))

These tests quickly catch row, column, and block consistency issues.

Common Pitfalls

  • Validating rows and columns but forgetting 3 by 3 blocks.
  • Accepting zeros or non-digit symbols in completed-grid validation mode.
  • Assuming input shape is always correct without checks.
  • Producing overly golfed code that is impossible to debug.
  • Comparing only group sums instead of full uniqueness sets.

Summary

  • Sudoku validation requires checking 27 groups: 9 rows, 9 columns, 9 blocks.
  • Start with a readable validator before golfing.
  • Use set-based group checks for concise and reliable logic.
  • Normalize input formats so validation code stays simple.
  • Keep challenge-style compactness separate from maintainable production code.

Course illustration
Course illustration

All Rights Reserved.