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
Difficulty
and has an acceptance rate of about 54% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Matrix
AI Disclaimer
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.
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
matrixis an empty list,nbecomes 0. Both the row and column loops have zero iterations, so the function reaches the finalreturn 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
maxcheck will detect that the maximum is less than n, causing aFalsereturn. -
Rows or columns with duplicate values - The
len(set(...)) != npart 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
mincheck, while any element larger than n triggers themaxcheck, 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, andset, 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
colfor 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
orin 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 36: Valid Sudoku
- problem 1572: Matrix Diagonal Sum
- problem 2661: First Completely Painted Row or Column
Solved On The Same Day
- problem 1957: Delete Characters to Make Fancy String
- problem 2806: Account Balance After Rounded Purchase
Extra
- 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