Check if Grid Satisfies Conditions
EasyPrompt
You are given a 2D matrix grid of size m x n. You need to check if each cell grid[i][j] is:
- Equal to the cell below it, i.e.
grid[i][j] == grid[i + 1][j](if it exists). - Different from the cell to its right, i.e.
grid[i][j] != grid[i][j + 1](if it exists).
Return true if all the cells satisfy these conditions, otherwise, return false.
Example 1:
Input: grid = [[1,0,2],[1,0,2]]
Output: true
Explanation:

All the cells in the grid satisfy the conditions.
Example 2:
Input: grid = [[1,1,1],[0,0,0]]
Output: false
Explanation:

All cells in the first row are equal.
Example 3:
Input: grid = [[1],[2],[3]]
Output: false
Explanation:

Cells in the first column have different values.
Constraints:
1 <= n, m <= 100 <= grid[i][j] <= 9
Approaches
2 approaches with complexity analysis and trade-offs.
This is the most efficient approach. It involves iterating through the grid just once. For each cell, it checks both the vertical and horizontal conditions simultaneously. If any condition is violated at any point, the function immediately returns false, which avoids unnecessary checks.
Algorithm
- Get the dimensions of the grid,
m(rows) andn(columns). - Iterate through each row
ifrom0tom-1. - Iterate through each column
jfrom0ton-1. - For the current cell
grid[i][j]:- If a cell below exists (
i < m - 1), check ifgrid[i][j] != grid[i+1][j]. If true, returnfalse. - If a cell to the right exists (
j < n - 1), check ifgrid[i][j] == grid[i][j+1]. If true, returnfalse.
- If a cell below exists (
- If the loops complete without returning
false, it means all conditions are satisfied. Returntrue.
Walkthrough
The algorithm iterates through every cell of the grid using nested loops, with the outer loop for rows (i) and the inner loop for columns (j).
For each cell grid[i][j], it performs two checks:
- Vertical Condition: It checks if the cell is equal to the one below it. This check is only necessary if there is a cell below, i.e.,
i < m - 1. Ifgrid[i][j] != grid[i + 1][j], the condition is violated, and the function returnsfalse. - Horizontal Condition: It checks if the cell is different from the one to its right. This check is only necessary if there is a cell to the right, i.e.,
j < n - 1. Ifgrid[i][j] == grid[i][j + 1], the condition is violated, and the function returnsfalse. These checks are performed for each cell. The boundary conditions (i < m - 1andj < n - 1) are crucial to prevent out-of-bounds errors when accessinggrid[i + 1][j]andgrid[i][j + 1]. If the loops complete without finding any violations, it means all cells in the grid satisfy the given conditions, and the function returnstrue.
class Solution { public boolean satisfiesConditions(int[][] grid) { int m = grid.length; int n = grid[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Check condition 1: Equal to the cell below if (i < m - 1) { if (grid[i][j] != grid[i + 1][j]) { return false; } } // Check condition 2: Different from the cell to its right if (j < n - 1) { if (grid[i][j] == grid[i][j + 1]) { return false; } } } } return true; }}Complexity
Time
O(m * n). The algorithm iterates through each cell of the grid at most once. In the worst case, it visits all `m * n` cells. In the best case, if a condition is violated at `grid[0][0]`, the complexity is O(1).
Space
O(1). No extra space proportional to the input size is used. The memory usage is constant.
Trade-offs
Pros
This is the most time-efficient approach as it combines both checks into a single pass.
It supports 'early exit', meaning it terminates as soon as a condition is violated, which can save significant time on large grids where a violation occurs early.
Cons
The logic within the loop is slightly more complex due to handling two conditions and their respective boundary checks simultaneously.
This approach breaks down the problem into two separate subproblems. First, it iterates through the grid to verify the vertical condition (all elements in a column must be the same). If this condition holds for all columns, it performs a second iteration to verify the horizontal condition (adjacent elements in a row must be different).
Algorithm
- Get the dimensions of the grid,
m(rows) andn(columns). - First Pass (Vertical Check):
- Iterate through each column
jfrom0ton-1. - Iterate through each row
ifrom0tom-2. - If
grid[i][j]is not equal togrid[i+1][j], returnfalse.
- Iterate through each column
- Second Pass (Horizontal Check):
- Iterate through each row
ifrom0tom-1. - Iterate through each column
jfrom0ton-2. - If
grid[i][j]is equal togrid[i][j+1], returnfalse.
- Iterate through each row
- If both passes complete, return
true.
Walkthrough
The algorithm first focuses on the column-wise constraint. It iterates through each column and, within each column, checks if every element is equal to the one directly below it.
The outer loop runs from j = 0 to n-1 (columns), and the inner loop runs from i = 0 to m-2 (rows, excluding the last).
Inside the inner loop, it checks if (grid[i][j] != grid[i + 1][j]). If this condition is ever true, it means a column has different values, so we can immediately return false.
If the first set of loops completes successfully, it means all columns satisfy the first condition.
Next, the algorithm checks the row-wise constraint. It iterates through each row and, within each row, checks if any element is equal to the one to its right.
The outer loop runs from i = 0 to m-1 (rows), and the inner loop runs from j = 0 to n-2 (columns, excluding the last).
Inside this second inner loop, it checks if (grid[i][j] == grid[i][j + 1]). If this is true, it violates the second condition, and we return false.
If both sets of loops complete without returning false, it means all conditions are met for all cells, and we can safely return true.
class Solution { public boolean satisfiesConditions(int[][] grid) { int m = grid.length; int n = grid[0].length; // Pass 1: Check vertical condition (grid[i][j] == grid[i + 1][j]) for (int j = 0; j < n; j++) { for (int i = 0; i < m - 1; i++) { if (grid[i][j] != grid[i + 1][j]) { return false; } } } // Pass 2: Check horizontal condition (grid[i][j] != grid[i][j + 1]) for (int i = 0; i < m; i++) { for (int j = 0; j < n - 1; j++) { if (grid[i][j] == grid[i][j + 1]) { return false; } } } return true; }}Complexity
Time
O(m * n). In the worst-case scenario, the algorithm iterates through the grid twice. The first pass takes O(m * n) time, and the second pass also takes O(m * n) time. The total time complexity is O(m * n) + O(m * n) = O(m * n).
Space
O(1). The algorithm uses only a few variables to store the dimensions and loop counters, so the space required is constant and does not depend on the size of the input grid.
Trade-offs
Pros
The logic is separated into two distinct parts, which can make the code easier to read and understand.
Each part handles exactly one of the problem's conditions.
Cons
It is potentially less efficient than a single-pass approach. If a horizontal condition fails (e.g.,
grid[0][0] == grid[0][1]), this approach will still complete the entire vertical check before finding the failure, leading to unnecessary computations.
Solutions
Solution
class Solution {public boolean satisfiesConditions(int[][] grid) { int m = grid.length, n = grid[0].length; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i + 1 < m && grid[i][j] != grid[i + 1][j]) { return false; } if (j + 1 < n && grid[i][j] == grid[i][j + 1]) { return false; } } } return true; }}class Solution: def satisfiesConditions(self, grid: List[List[int]]) -> bool: m, n = len(grid), len(grid[0]) for i, row in enumerate(grid): for j, x in enumerate(row): if i + 1 < m and x != grid[i + 1][j]: return False if j + 1 < n and x == grid[i][j + 1]: return False return Trueclass Solution {public: bool satisfiesConditions(vector<vector<int>> &grid) { int m = grid.size(), n = grid[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i + 1 < m && grid[i][j] != grid[i + 1][j]) { return false; } if (j + 1 < n && grid[i][j] == grid[i][j + 1]) { return false; } } } return true; }};Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.