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.
- Create a result matrix of the same dimensions.
- For each cell (r,c):
- Initialize a
sum and a count.
- Iterate through the 3x3 window from r−1 to r+1 and c−1 to c+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 3imes3 with all 10s except (0,0) is 100.
- Cell (0,0): Neighbors (0,0), (0,1), (1,0), (1,1).
- Sum = 100+10+10+10=130. Count = 4.
- Average = 130/4=32.
- Result (0,0) = 32.
- Cell (1,1): Has all 9 neighbors. Sum = 100+8imes10=180. Count = 9.
- 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.