We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Grid Satisfies Conditions

Number: 3415

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

You are given an m x n 2D matrix named grid. For each cell grid[i][j], you need to check two conditions:

  1. If a cell directly below exists (i.e. grid[i+1][j]), then it must be equal to grid[i][j].
  2. If a cell to the right exists (i.e. grid[i][j+1]), then it must be different from grid[i][j]. Return true if all cells satisfy these conditions; otherwise, return false.

Key Insights

  • Iterate through every cell of the grid.
  • For each cell, check the cell below (if it exists) to ensure equality.
  • Check the cell to the right (if it exists) to ensure inequality.
  • Early exit from the loop if any condition fails.
  • The grid size is small (max 10 x 10), so a straightforward nested iteration is efficient.

Space and Time Complexity

Time Complexity: O(m * n), where m and n are the dimensions of the grid. Space Complexity: O(1), as only constant extra space is used.


Solution

We use a simple brute-force approach by iterating through each cell of the grid with nested loops. At each cell, we check:

  1. If the cell below exists and whether it is equal to the current cell.
  2. If the cell to the right exists and whether it is different than the current cell. If any cell does not meet its respective condition, we return false immediately. If all cells meet the required conditions, we return true at the end. The solution leverages simple iteration and conditional checks, ensuring clarity and efficiency given the small input size.

Code Solutions

# Function to check if the grid satisfies the conditions
def checkGrid(grid):
    # Get the number of rows and columns
    rows = len(grid)
    cols = len(grid[0])
    
    for i in range(rows):
        for j in range(cols):
            # If a cell below exists, check if it is equal to the current cell
            if i + 1 < rows:
                # If the cell below is not equal, return False
                if grid[i][j] != grid[i + 1][j]:
                    return False
            # If a cell to the right exists, check if it is different from the current cell
            if j + 1 < cols:
                # If the cell to the right is equal, return False
                if grid[i][j] == grid[i][j + 1]:
                    return False
    # All cells satisfy the conditions, return True
    return True

# Example usage:
grid = [[1,0,2],[1,0,2]]
print(checkGrid(grid))  # Expected output: True
← Back to All Questions