Magicsheet logo

Image Smoother

Easy
38.3%
Updated 6/1/2025

Image Smoother

What is this problem about?

The Image Smoother coding problem asks you to apply a "box filter" to a 2D grid of integers. For each cell in the grid, you calculate the average of its value and the values of its 8 surrounding neighbors (3x3 area). If a cell is on the boundary, you only average the existing neighbors. The result for each cell is the floor of the average.

Why is this asked in interviews?

Companies like Adobe, Meta, and Amazon use this "Easy" question to test basic matrix manipulation and boundary handling. It’s a core component of image processing (blurring/smoothing). It evaluates whether you can write clean, readable code that handles edge cases (corners and sides) without repeating logic.

Algorithmic pattern used

This is a Matrix Simulation problem.

  1. Create a result matrix of the same dimensions.
  2. For each cell (r,c)(r, c):
    • Initialize a sum and a count.
    • Iterate through the 3x3 window from r1r-1 to r+1r+1 and c1c-1 to c+1c+1.
    • Inside the window loop, check if the neighbor coordinates are within the grid boundaries.
    • If valid, add the neighbor's value to sum and increment count.
    • Store floor(sum / count) in the result matrix.

Example explanation

Grid 3imes33 imes 3 with all 10s except (0,0) is 100.

  1. Cell (0,0): Neighbors (0,0), (0,1), (1,0), (1,1).
  2. Sum = 100+10+10+10=130100 + 10 + 10 + 10 = 130. Count = 4.
  3. Average = 130/4=32130 / 4 = 32.
  4. Result (0,0) = 32.
  5. Cell (1,1): Has all 9 neighbors. Sum = 100+8imes10=180100 + 8 imes 10 = 180. Count = 9.
  6. Result (1,1) = 20.

Common mistakes candidates make

  • In-place modification: Updating the original grid while still reading from it for other cells. This "pollutes" the averages. Always use a copy or a new matrix.
  • Hard-coded boundary checks: Writing separate code for corners, edges, and the interior. Using a nested loop from -1 to 1 with an isValid() check is much cleaner.
  • Integer Division: Not being careful with rounding (though the problem usually specifies floor division).

Interview preparation tip

Practice the "Neighbor Loop" pattern: for dr in [-1, 0, 1]: for dc in [-1, 0, 1]:. This approach is extensible to any neighborhood size and prevents the "if-else" nightmare often seen in beginner solutions for grid problems.

Similar Questions