#2133

Check if Every Row and Column Contains All Numbers

Easy
ArrayHash TableMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of using sets for each row and column, we can use a single array to track occurrences of numbers. This reduces the overhead of creating sets and allows us to check validity more efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two arrays of size n initialized to zero, one for rows and one for columns.
  2. 2Step 2: Iterate through each element in the matrix, incrementing the corresponding row and column counts.
  3. 3Step 3: After filling the counts, check if each row and column has exactly one occurrence of each number from 1 to n.
  4. 4Step 4: If any row or column fails this check, return false; otherwise, return true.
solution.py12 lines
1def checkMatrix(matrix):
2    n = len(matrix)
3    row_count = [0] * n
4    col_count = [0] * n
5    for i in range(n):
6        for j in range(n):
7            num = matrix[i][j] - 1
8            row_count[i] += 1
9            col_count[j] += 1
10            if row_count[i] > n or col_count[j] > n:
11                return False
12    return True if all(count == n for count in row_count) and all(count == n for count in col_count) else False

Complexity note: The time complexity is O(n) because we only need to iterate through the matrix once, and the space complexity is O(n) due to the row and column count arrays.

  • 1Every row and column must contain unique integers from 1 to n.
  • 2Using sets can simplify checking for duplicates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.