Image Smoother — LeetCode 661 Python Solution

EasyArrayMatrix
Problem
#661
Reading time
3 min

The 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).

Example

Input
img = [[1,1,1],[1,0,1],[1,1,1]]
Output
[[0,0,0],[0,0,0],[0,0,0]]
Explanation
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0

Python solution

Python
class Solution:
    def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
        m, n = len(img), len(img[0])
        ans = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                s = cnt = 0
                for x in range(i - 1, i + 2):
                    for y in range(j - 1, j + 2):
                        if 0 <= x < m and 0 <= y < n:
                            cnt += 1
                            s += img[x][y]
                ans[i][j] = s // cnt
        return ans

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns of \textit{img}, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 661. Image Smoother is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 661. Image Smoother?
LeetCode 661. Image Smoother is rated Easy on LeetCode.
What is the time complexity of LeetCode 661. Image Smoother?
The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of \textit{img}, respectively.
What is the space complexity of LeetCode 661. Image Smoother?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 661. Image Smoother cover?
LeetCode 661. Image Smoother is tagged Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview