Leetcode 2133: Check if Every Row and Column Contains All Numbers

grid47
grid47
Exploring patterns and algorithms
Apr 7, 2024 5 min read

You are given an n x n matrix where each element is an integer. The matrix is considered valid if every row and every column contains all the integers from 1 to n (inclusive). Your task is to check whether the given matrix satisfies this condition. Return true if the matrix is valid, and false otherwise.
Problem
Approach
Steps
Complexity
Input: The input is a square matrix represented by a 2D array of size n x n, where each element is an integer between 1 and n.
Example: matrix = [[1,2,3],[3,1,2],[2,3,1]]
Constraints:
• n == matrix.length == matrix[i].length
• 1 <= n <= 100
• 1 <= matrix[i][j] <= n
Output: Return a boolean value: true if the matrix is valid, otherwise return false.
Example: Input: matrix = [[1, 2, 3], [3, 1, 2], [2, 3, 1]] Output: true
Constraints:
• The solution must return true if the matrix satisfies the condition, otherwise false.
Goal: The goal is to verify if every row and column contains all the integers from 1 to n.
Steps:
• 1. Iterate over each row and check if it contains all integers from 1 to n.
• 2. Iterate over each column and check if it contains all integers from 1 to n.
• 3. If both row and column conditions are satisfied, return true; otherwise, return false.
Goal: The problem requires checking the matrix's validity efficiently for matrices of size up to 100 x 100.
Steps:
• The matrix will always be square (n x n).
• The elements in the matrix will always be between 1 and n, inclusive.
Assumptions:
• The matrix will always have valid integer entries between 1 and n.
Input: Input: matrix = [[1, 2, 3], [3, 1, 2], [2, 3, 1]]
Explanation: In this case, n = 3, and every row and column contains the integers 1, 2, and 3. Therefore, the matrix is valid, and the output is true.

Input: Input: matrix = [[1, 1, 1], [1, 2, 3], [1, 2, 3]]
Explanation: Here, the first row and first column do not contain all integers from 1 to 3. Therefore, the matrix is not valid, and the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus