algoadvance

Given an m x n integer matrix image representing the grayscale of an image, return a new matrix answer of the same dimensions where:

Clarifying Questions

  1. Q: What is the range of values in the input matrix image?
    • A: The values in the matrix can be any integer, positive or negative.
  2. Q: How should edge cases be handled (e.g., single-row or single-column matrices)?
    • A: The calculation should only consider cells within the matrix boundaries for such edge cases.
  3. Q: Is there a constraint on the size of the matrix?
    • A: The matrix dimensions can be any size, up to m x n.

Strategy

  1. Iterate through each cell in the matrix.
  2. For each cell, calculate the average of the 3x3 window centered at that cell.
  3. Ensure boundary checks to avoid accessing elements outside the matrix.
  4. Store the computed average in the corresponding cell of the result matrix.

Time Complexity

Code

def imageSmoother(image):
    if not image or not image[0]:
        return []

    m, n = len(image), len(image[0])
    result = [[0] * n for _ in range(m)]

    for row in range(m):
        for col in range(n):
            # Initialize sum of elements and count of valid elements.
            sum_val, count = 0, 0
            # Iterate over the 3x3 window.
            for i in range(row - 1, row + 2):
                for j in range(col - 1, col + 2):
                    if 0 <= i < m and 0 <= j < n:
                        sum_val += image[i][j]
                        count += 1
            # Calculate result for the current cell.
            result[row][col] = sum_val // count

    return result

Explanation

This solution ensures that all boundary conditions are respected, and the computation of the smoothed values is efficient and straightforward.

Try our interview co-pilot at AlgoAdvance.com