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
102102โœ… Valid PatternVertical: Same | Horizontal: Different1100โŒ Invalid PatternHorizontal: Same (Violation!)
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.
Asked in
Amazon 15 Microsoft 12 Google 8 Meta 6
28.5K Views
Medium Frequency
~8 min Avg. Time
834 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