Check if Grid Satisfies Conditions - Problem

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.

Input & Output

Example 1 — Valid Grid
$ Input: grid = [[1,0,2],[1,0,2]]
Output: true
💡 Note: All cells in each column are equal (1,1), (0,0), (2,2). Adjacent columns differ: 1≠0, 0≠2. All conditions satisfied.
Example 2 — Invalid Vertical
$ Input: grid = [[1,1,1],[0,0,0]]
Output: false
💡 Note: Column values are not uniform: grid[0][0]=1 but grid[1][0]=0. Also adjacent columns are same: grid[0][0]==grid[0][1]. Fails both conditions.
Example 3 — Invalid Horizontal
$ Input: grid = [[1],[2]]
Output: false
💡 Note: Single column grid with two rows: grid[0][0]=1 and grid[1][0]=2. Since 1≠2, the vertical condition fails.

Constraints

  • 1 ≤ m, n ≤ 10
  • 1 ≤ grid[i][j] ≤ 9

Visualization

Tap to expand
Grid Conditions Validator INPUT 2D Grid (2x3): 1 0 2 1 0 2 j=0 j=1 j=2 i=0 i=1 Conditions to Check: 1. Vertical: Same value grid[i][j] == grid[i+1][j] 2. Horizontal: Different grid[i][j] != grid[i][j+1] ALGORITHM STEPS 1 Iterate by columns Process each column j 2 Check vertical equality Compare grid[i][j] with grid[i+1][j] 3 Check horizontal diff Compare grid[i][j] with grid[i][j+1] 4 Return result true if all pass, else false Column-wise Validation: Col 0: 1==1 [OK] 1!=0 [OK] Col 1: 0==0 [OK] 0!=2 [OK] Col 2: 2==2 [OK] (no right) All checks pass! FINAL RESULT 1 0 2 1 0 2 || || || != != != != Output: true Grid satisfies all conditions: Columns equal, rows different Key Insight: Column-wise validation is efficient: iterate through each column, checking vertical equality and horizontal difference in a single pass. Time complexity: O(m*n), Space: O(1). TutorialsPoint - Check if Grid Satisfies Conditions | Column-wise Validation Approach
Asked in
Google 12 Meta 8 Microsoft 6
8.5K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen