Image Smoother (LeetCode 661): Solution and Explanation

Easy
Array
Matrix

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

  1. Create res with the same shape as img.
  2. For each cell (i, j), set total = 0 and count = 0.
  3. Loop x over max(0, i - 1) to min(m - 1, i + 1) and y over max(0, j - 1) to min(n - 1, j + 1), adding img[x][y] to total and one to count.
  4. Store res[i][j] = total // count.
  5. Return res.

Step-by-step example

img = [[1,1,1],[1,0,1],[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.
  2. Edge (0,1): six cells with total 5, so res = 5 // 6 = 0.
  3. Center (1,1): all nine cells with total 8, so res = 8 // 9 = 0.
  4. 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 res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each of the m * n cells reads at most 9 input values.

Space

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.