Image Smoother - Problem

An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother).

If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).

Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.

Input & Output

Example 1 — Basic 2x3 Matrix
$ Input: img = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
💡 Note: For each cell, calculate average of itself and valid neighbors. Center cell (1,1) has value 0, surrounded by eight 1s: (1+1+1+1+0+1+1+1+1)/9 = 8/9 = 0 (floor division)
Example 2 — Edge Cell Handling
$ Input: img = [[100,200,100],[200,50,200],[100,200,100]]
Output: [[137,141,137],[141,138,141],[137,141,137]]
💡 Note: Corner cells only have 4 neighbors (3 neighbors + itself). Top-left: (100+200+200+50)/4 = 550/4 = 137. Edge cells have 6 neighbors total.
Example 3 — Single Cell
$ Input: img = [[1]]
Output: [[1]]
💡 Note: Single cell matrix - only the cell itself is considered: 1/1 = 1

Constraints

  • m == img.length
  • n == img[i].length
  • 1 ≤ m, n ≤ 200
  • 0 ≤ img[i][j] ≤ 255

Visualization

Tap to expand
Image Smoother: 3×3 Averaging FilterInput Image1111011113×3 FilterAverage neighborsSmoothed Result000000000Example: Center cell (1,1) = (1+1+1+1+0+1+1+1+1) ÷ 9 = 8 ÷ 9 = 0Each cell becomes the floor of the average of itself and valid neighbors🎯 Edge/corner cells have fewer neighbors but same averaging principleTime: O(m×n) | Space: O(m×n)
Understanding the Visualization
1
Input Matrix
Original image with integer pixel values
2
Apply 3x3 Filter
For each cell, average itself + valid neighbors
3
Smoothed Output
Result matrix with averaged values
Key Takeaway
🎯 Key Insight: Handle boundary conditions by only averaging available neighbors, not assuming 9 cells
Asked in
Google 25 Amazon 18 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 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