Check if Every Row and Column Contains All Numbers — LeetCode 2133 Python Solution

EasyArrayHash TableMatrix
Problem
#2133
Reading time
2 min

The problem

An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid.

Example

Input
matrix = [[1,2,3],[3,1,2],[2,3,1]]
Output
true
Explanation
In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.

Python solution

Python
class Solution:
    def checkValid(self, matrix: List[List[int]]) -> bool:
        n = len(matrix)
        return all(len(set(row)) == n for row in chain(matrix, zip(*matrix)))

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2133. Check if Every Row and Column Contains All Numbers is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2133. Check if Every Row and Column Contains All Numbers?
LeetCode 2133. Check if Every Row and Column Contains All Numbers is rated Easy on LeetCode.
What is the time complexity of LeetCode 2133. Check if Every Row and Column Contains All Numbers?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2133. Check if Every Row and Column Contains All Numbers?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2133. Check if Every Row and Column Contains All Numbers cover?
LeetCode 2133. Check if Every Row and Column Contains All Numbers is tagged Array, Hash Table and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview