Check if Grid Satisfies Conditions - Problem
You are given a 2D matrix grid of size m ร n. Your task is to validate whether this grid follows a specific pattern:
- Vertical Consistency: Each cell must be equal to the cell directly below it (if it exists)
- Horizontal Diversity: Each cell must be different from the cell to its right (if it exists)
In other words, values should be consistent within columns but vary across rows. Think of it like a striped pattern where each column has the same color throughout, but adjacent columns have different colors.
Goal: Return true if all cells satisfy both conditions, otherwise return false.
Input & Output
example_1.py โ Valid Grid
$
Input:
grid = [[1,0,2],[1,0,2]]
โบ
Output:
true
๐ก Note:
Each column has consistent values (1,1), (0,0), (2,2) and adjacent columns have different values (1โ 0, 0โ 2)
example_2.py โ Invalid Horizontal
$
Input:
grid = [[1,1,1],[0,0,0]]
โบ
Output:
false
๐ก Note:
Adjacent cells in the same row have the same values, violating the horizontal diversity rule
example_3.py โ Invalid Vertical
$
Input:
grid = [[1],[2]]
โบ
Output:
false
๐ก Note:
The single column has different values (1โ 2), violating the vertical consistency rule
Constraints
- 1 โค m, n โค 10
- 1 โค grid[i][j] โค 1000
- grid[i][j] contains only positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Check Vertical
Ensure each column has consistent values from top to bottom
2
Check Horizontal
Ensure adjacent columns have different values
3
Early Exit
Return false immediately when any violation is found
Key Takeaway
๐ฏ Key Insight: We only need one pass since we're checking local relationships between adjacent cells, making this an optimal O(mรn) solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code