#3142
Check if Grid Satisfies Conditions
EasyArrayMatrixArrayMatrix
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(m + n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(m + n)Space O(1)
We can optimize our checks by first ensuring that all cells in each column are the same. If this condition is satisfied, we only need to check adjacent columns for differences in their first cells.
⚙️
Algorithm
5 steps- 1Step 1: Iterate through each column to check if all cells in that column are the same.
- 2Step 2: If any column fails this check, return false.
- 3Step 3: If all columns pass, check the first cell of each column to ensure they are different.
- 4Step 4: If any adjacent columns have the same first cell, return false.
- 5Step 5: If all checks pass, return true.
solution.py12 lines
1# Full working Python code
2
3def checkGrid(grid):
4 m, n = len(grid), len(grid[0])
5 for j in range(n):
6 for i in range(1, m):
7 if grid[i][j] != grid[i - 1][j]:
8 return False
9 for j in range(n - 1):
10 if grid[0][j] == grid[0][j + 1]:
11 return False
12 return Trueℹ
Complexity note: The optimal solution checks each column for equality and then checks adjacent columns for differences, leading to a time complexity of O(m + n). The space complexity remains O(1) as we are not using additional data structures.
- 1Each column must have the same value.
- 2Adjacent columns must have different values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.