Image Smoother (LeetCode 661): Solution and Explanation
Given an m x n grayscale image, replace every pixel by the rounded-down average of itself and its existing neighbors in the surrounding 3 x 3 block.
Intuition
Smoothing is a local operation: each output pixel depends only on the 3 x 3 block around the same position in the input.
At the borders part of that block falls off the image. Those positions are not zeros, they are simply missing, so the divisor shrinks too: 4 for a corner, 6 for an edge, 9 inside.
Every average must use the original values. Writing into a separate result matrix guarantees that a pixel you already smoothed never leaks into its neighbor's average.
Approach: Clipped 3 x 3 window
- Create
reswith the same shape asimg. - For each cell
(i, j), settotal = 0andcount = 0. - Loop
xovermax(0, i - 1)tomin(m - 1, i + 1)andyovermax(0, j - 1)tomin(n - 1, j + 1), addingimg[x][y]tototaland one tocount. - Store
res[i][j] = total // count. - Return
res.
Step-by-step example
img = [[1,1,1],[1,0,1],[1,1,1]]
- Corner (0,0): the window holds 1, 1, 1, 0, a total of 3 over 4 cells, so res = 3 // 4 = 0.
- Edge (0,1): six cells with total 5, so res = 5 // 6 = 0.
- Center (1,1): all nine cells with total 8, so res = 8 // 9 = 0.
- Every other cell is a corner or an edge with the same sums, so the whole result is zeros.
Code: Python, Java, C++
1class Solution:
2 def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
3 m, n = len(img), len(img[0])
4 res = [[0] * n for _ in range(m)]
5 for i in range(m):
6 for j in range(n):
7 total = count = 0
8 for x in range(max(0, i - 1), min(m, i + 2)):
9 for y in range(max(0, j - 1), min(n, j + 2)):
10 total += img[x][y]
11 count += 1
12 res[i][j] = total // count
13 return res1class Solution {
2 public int[][] imageSmoother(int[][] img) {
3 int m = img.length, n = img[0].length;
4 int[][] res = new int[m][n];
5 for (int i = 0; i < m; i++) {
6 for (int j = 0; j < n; j++) {
7 int total = 0, count = 0;
8 for (int x = Math.max(0, i - 1); x <= Math.min(m - 1, i + 1); x++) {
9 for (int y = Math.max(0, j - 1); y <= Math.min(n - 1, j + 1); y++) {
10 total += img[x][y];
11 count++;
12 }
13 }
14 res[i][j] = total / count;
15 }
16 }
17 return res;
18 }
19}1class Solution {
2public:
3 vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
4 int m = img.size(), n = img[0].size();
5 vector<vector<int>> res(m, vector<int>(n, 0));
6 for (int i = 0; i < m; i++) {
7 for (int j = 0; j < n; j++) {
8 int total = 0, count = 0;
9 for (int x = max(0, i - 1); x <= min(m - 1, i + 1); x++) {
10 for (int y = max(0, j - 1); y <= min(n - 1, j + 1); y++) {
11 total += img[x][y];
12 count++;
13 }
14 }
15 res[i][j] = total / count;
16 }
17 }
18 return res;
19 }
20};Time and space complexity
O(m * n)
Each of the m * n cells reads at most 9 input values.
O(m * n)
The result matrix has the same size as the image. Apart from it, only a few counters are used.
Other approaches
In place with bit packing (time O(m * n), space O(1))
Values fit in 8 bits, so the smoothed value can be stored in the upper bits of each cell (img[i][j] |= avg << 8) while the low 8 bits still hold the original. A final pass shifts everything down. This saves the extra matrix.
2D prefix sums (time O(m * n), space O(m * n))
Build a prefix sum table, then get each window total in O(1) with four lookups. It pays off for larger kernels; for a 3 x 3 window the direct loop is just as fast.
Common mistakes
- Smoothing in place without preserving the original values, so later cells average already-changed pixels.
- Always dividing by 9, which treats missing border cells as zeros and darkens the edges.
- Rounding to nearest instead of down. The problem asks for the floor of the average.
Frequently asked questions
How many cells are in a window?
Nine for an inner cell, six on an edge, four in a corner. A single row or column has fewer still: the ends of a 1 x n image average only 2 cells.
Can the total overflow?
No. At most 9 values of up to 255 are added, so the total is at most 2295.
Why not treat out-of-range neighbors as 0?
The problem defines the average over the cells that exist. Padding with zeros would change both the total and the divisor and give darker borders.