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

Master LeetCode problem 2133 (Check if Every Row and Column Contains All Numbers), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2133. Check if Every Row and Column Contains All Numbers

Problem Explanation

Explanation

To solve this problem, we can iterate through each row and column of the matrix and check if they contain all the integers from 1 to n. We can use sets to keep track of the unique numbers in each row and column. If any row or column does not contain all the numbers from 1 to n, we return false. Otherwise, we return true.

  • Time complexity: O(n^2) where n is the size of the matrix
  • Space complexity: O(n)

Solution Code

class Solution {
    public boolean isMatrixValid(int[][] matrix) {
        int n = matrix.length;
        
        for (int i = 0; i < n; i++) {
            Set<Integer> rowSet = new HashSet<>();
            Set<Integer> colSet = new HashSet<>();
            
            for (int j = 0; j < n; j++) {
                if (rowSet.contains(matrix[i][j]) || colSet.contains(matrix[j][i])) {
                    return false;
                }
                rowSet.add(matrix[i][j]);
                colSet.add(matrix[j][i]);
            }
            
            if (rowSet.size() != n || colSet.size() != n) {
                return false;
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2133 (Check if Every Row and Column Contains All Numbers)?

This page provides optimized solutions for LeetCode problem 2133 (Check if Every Row and Column Contains All Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2133 (Check if Every Row and Column Contains All Numbers)?

The time complexity for LeetCode 2133 (Check if Every Row and Column Contains All Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2133 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2133 in Java, C++, or Python.

Back to LeetCode Solutions