You are given a grayscale picture as a grid img of whole numbers. To smooth it, replace every cell with the average of the 3×3 block centred on it: the cell itself and its up to eight neighbours. Neighbours that fall outside the picture are simply left out, so a corner averages 4 cells and an edge cell averages 6.
Each average is rounded down to a whole number. Every average uses the original values, not ones already smoothed. Return the smoothed grid.
Example 1
Input: img = [[12, 4], [8, 0], [1, 3]] Output: [[6, 6], [4, 4], [3, 3]] Why: top row: 24 // 4 = 6; middle: 28 // 6 = 4; bottom: 12 // 4 = 3
2 more examples and the constraints
Example 2
Input: img = [[10, 50, 30]] Output: [[30, 30, 40]] Why: 60 // 2, 90 // 3 and 80 // 2
Example 3
Input: img = [[7]] Output: [[7]] Why: a lone pixel only averages itself
Constraints
- 1 ≤ m, n ≤ 200, where img has m rows and n columns
- 0 ≤ img[i][j] ≤ 255
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Visit every neighbourO(m·n·9)
- 2D prefix sumsO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Reads for a 200 × 200 image | Verdict |
|---|---|---|---|
| Visit every neighbour | O(m·n·9) | Passes; simple | |
| 2D prefix sums | O(m·n) | Best; any window size |
m and n are the image’s rows and columns. Both are linear; prefix sums read 4 table cells per pixel instead of up to 9.
Edge cases to test
- One pixel. The window holds only the cell itself, so the value is unchanged.
- One row or one column. Ends average 2 cells and the rest 3.
- Corners and edges. They average 4 and 6 cells; never divide by 9 everywhere.
- Rounding. Use integer division (floor). The values are never negative, so truncation and floor agree.
Common mistakes
- Writing averages back into
imgwhile later cells still need the old values. - Always dividing by 9, even on the border.
- Getting the prefix-sum corners off by one; the extra zero row and column avoid most of these.
How to talk through it
- 1Clarify. Do border cells use fewer neighbours? Is the average rounded down?
- 2Give the direct loop. Clamp the 3×3 window, sum and count, write into a new grid.
- 3State the cost. At most 9 reads per cell, so O(m·n) already.
- 4Offer prefix sums. Four lookups per window, whatever its size.
- 5Test out loud. Try a single pixel, a single row and a 2×2 grid.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?