Problem 2133

Abstract / Summary

Check if every row and column in a grid contains all numbers from 1 to n exactly once.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2133.py

class Solution:
    def checkValid(self, matrix: List[List[int]]) -> bool:
        n = len(matrix)

        # horizontal
        for y in range(n):
            if min(matrix[y]) != 1 or max(matrix[y]) != n or len(set(matrix[y])) != n:
                return False

        # vertical
        for x in range(n):
            col = []
            for y in range(n):
                col.append(matrix[y][x])
            if min(col) != 1 or max(col) != n or len(set(col)) != n:
                return False

        return True
18 lines | 541 bytes | submitted December 14, 2023 | GitHub   15% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method checkValid that determines whether a square integer matrix satisfies the constraints of a Latin square: each row and each column must contain every integer from 1 up to n exactly once, where n is the dimension of the matrix. The algorithm proceeds in two phases-row validation followed by column validation-returning False immediately upon detecting any violation and True only after all checks succeed.

Row (horizontal) validation

The first loop iterates over each row index y. For every row the code extracts the list matrix[y] and performs three distinct checks in a single conditional expression:

if min(matrix[y]) != 1 or max(matrix[y]) != n or len(set(matrix[y])) != n:
    return False

The min check guarantees that the smallest element is 1, the max check guarantees that the largest element is n, and the len(set(...)) check confirms that all elements are unique, which together enforce the presence of the complete range [1, n] without duplication. Because the condition is evaluated row-by-row, the method can abort as soon as a single row fails, avoiding unnecessary work on the remaining rows.

Column (vertical) validation

After rows have been verified, the method proceeds to column validation. The outer loop iterates over each column index x. Inside, a temporary list col is built by appending the element at position [y][x] for every row y:

col = []
for y in range(n):
    col.append(matrix[y][x])

Once the column list is assembled, the same three checks used for rows are applied:

if min(col) != 1 or max(col) != n or len(set(col)) != n:
    return False

This mirrors the row logic, ensuring that each column also contains the full set of integers from 1 to n exactly once. The column list is constructed on demand for each column, which keeps memory usage limited to a single column at a time.

Early termination strategy

A notable characteristic of the implementation is its early-exit strategy. Both the row and column phases contain a return False statement inside the validation condition. As soon as any row or column violates the Latin-square property, the function stops further processing and returns False. This approach prevents the algorithm from performing redundant checks once a failure is known, which is especially beneficial for large matrices where an early defect can save considerable work.

Edge-case handling

The code implicitly handles several edge conditions:

  • Empty matrix - When matrix is an empty list, n becomes 0. Both the row and column loops have zero iterations, so the function reaches the final return True. An empty matrix trivially satisfies the definition because there are no rows or columns to violate the constraints.

  • Rows or columns with missing values - If a row or column lacks the full range (for example, containing only numbers 1 through n-1), the max check will detect that the maximum is less than n, causing a False return.

  • Rows or columns with duplicate values - The len(set(...)) != n part catches any duplication because converting the list to a set removes duplicates, reducing its length below n.

  • Values outside the allowed range - Any element smaller than 1 triggers the min check, while any element larger than n triggers the max check, both leading to early termination.

Performance-related observations

The implementation exhibits several practical optimizations:

  • Constant-time checks per row/column - By using built-in functions min, max, and set, the code leverages highly optimized C-level operations for each row and column, which are faster than manual loops in pure Python.

  • Minimal auxiliary storage - The column validation constructs only a single temporary list col for the current column, discarding it before moving to the next column. This keeps auxiliary memory proportional to n rather than n².

  • Avoidance of full matrix transposition - Instead of creating a transposed copy of the matrix, the algorithm extracts column elements on the fly, eliminating the overhead of an additional O(n²) data structure.

  • Short-circuit logical operators - The use of or in the conditional expression ensures that once a failing condition is found (e.g., min(matrix[y]) != 1), the remaining checks are not evaluated for that row, saving a small amount of computation.

Overall, the method delivers a straightforward and efficient verification of the Latin-square property by combining early exits, built-in operations, and careful management of temporary data.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a square grid filled with numbers, like a puzzle board. The goal is to make sure every row and every column contains each number from one to the size of the square exactly once.

First, the code looks at every row one by one. It checks three things to see if the row is correct. It makes sure the smallest number is a one and the biggest number is the same as the total size of the square. Then, it uses a special trick to check if every number is unique, making sure there are no copies of the same digit. If any of these rules are broken, it knows the puzzle is not finished correctly.

Next, the code does the same thing for all the columns. Since the columns go up and down, it carefully picks out the numbers one by one to form a list for each column. Just like before, it checks if the smallest is one, the biggest is the size of the square, and if every number is different. If everything looks good after checking every single row and every single column, the puzzle is solved.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 0.92

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
23 links | 12 authors | 8 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

3 solutions   December 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality