Solving Leetcode Interviews in Seconds with AI: Check if Every Row and Column Contains All Numbers
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2133" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Otherwise, return false. Example 1: 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. Hence, we return true. Example 2: Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] Output: false Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. Hence, we return false. Constraints: n == matrix.length == matrix[i].length 1 <= n <= 100 1 <= matrix[i][j] <= n
Explanation
Here's the breakdown:
Key Idea: Use sets to efficiently check if each row and each column contains all numbers from 1 to n. Iterate through rows and columns, adding elements to a set. If the size of the set after iterating a row/column isn't
n, or if the set contains elements outside the range[1, n], the matrix is invalid.Efficiency: The use of sets provides near-constant time complexity for checking the existence of elements, which optimizes the validation process.
Complexity:
- Runtime Complexity: O(n^2) - iterating through each element of the n x n matrix.
- Storage Complexity: O(n) - using sets of size at most n to validate each row and column.
Code
def check_valid_matrix(matrix: list[list[int]]) -> bool:
"""
Checks if an n x n matrix is valid, meaning every row and column contains all integers from 1 to n.
Args:
matrix: The n x n integer matrix.
Returns:
True if the matrix is valid, False otherwise.
"""
n = len(matrix)
# Check rows
for row in matrix:
row_set = set(row)
if len(row_set) != n:
return False
for num in row_set:
if not (1 <= num <= n):
return False
# Check columns
for col in range(n):
col_set = set()
for row in range(n):
col_set.add(matrix[row][col])
if len(col_set) != n:
return False
for num in col_set:
if not (1 <= num <= n):
return False
return True