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 - Helper Function Approach INPUT 3x3 Grayscale Image Matrix 1 1 1 1 0 1 1 1 1 Input Array: img = [[1,1,1], [1,0,1],[1,1,1]] Apply 3x3 smoothing filter to each cell m=3, n=3 ALGORITHM STEPS 1 Create Helper getAverage(i,j) function handles boundary checks 2 Iterate All Cells For each (i,j) in matrix call helper function 3 Sum Valid Neighbors Check 3x3 window bounds Sum values, count cells 4 Compute Average floor(sum / count) Store in result matrix Example: Center Cell (1,1) Neighbors: 1+1+1+1+0+1+1+1+1 Sum = 8, Count = 9 Average = floor(8/9) = 0 Corner cell (0,0): 4 neighbors floor(4/4) = 1... wait, = 0 floor(3/4) = 0 FINAL RESULT Smoothed Image Matrix 0 0 0 0 0 0 0 0 0 Output Array: [[0,0,0],[0,0,0],[0,0,0]] OK - All cells = 0 Time: O(m*n) Space: O(m*n) Key Insight: The Helper Function encapsulates boundary checking logic, making the main loop clean and readable. For each cell, we iterate through a 3x3 window, validate bounds, sum valid neighbors, and compute floor average. This avoids complex conditional logic in the main iteration by delegating boundary handling to a dedicated function. TutorialsPoint - Image Smoother | Helper Function Approach
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