KatInterview

661. Image Smoother

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to apply a 3x3 smoothing filter to each pixel of a 2D matrix representing a grayscale image. The new value for a pixel is the average of its own value and the values of its eight surrounding neighbors. For pixels at the edges or corners, the average is calculated using only the neighbors that exist within the image boundaries. The result of the average must be rounded down to the nearest integer (floor division).

Solution

Image Smoother in Python

class Solution:
    def imageSmoother(self, img: list[list[int]]) -> list[list[int]]:
        m, n = len(img), len(img[0])
        
        # Create a new matrix to store the smoothed image.
        result = [[0] * n for _ in range(m)]
        
        # Iterate over each cell of the image.
        for i in range(m):
            for j in range(n):
                total_sum = 0
                count = 0
                
                # Iterate over the 3x3 neighborhood of the cell (i, j).
                # The ranges automatically handle boundary conditions.
                for ni in range(max(0, i - 1), min(m, i + 2)):
                    for nj in range(max(0, j - 1), min(n, j + 2)):
                        total_sum += img[ni][nj]
                        count += 1
                
                # Calculate the average and store it in the result matrix.
                # Floor division // is used.
                result[i][j] = total_sum // count
        
        return result

Image Smoother in Java

class Solution {
    public int[][] imageSmoother(int[][] img) {
        int m = img.length;
        int n = img[0].length;
        
        // Create a new matrix to store the smoothed image.
        int[][] result = new int[m][n];
        
        // Iterate over each cell of the image.
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int sum = 0;
                int count = 0;
                
                // Iterate over the 3x3 neighborhood of the cell (i, j).
                for (int ni = i - 1; ni <= i + 1; ni++) {
                    for (int nj = j - 1; nj <= j + 1; nj++) {
                        // Check if the neighbor is within the image boundaries.
                        if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                            sum += img[ni][nj];
                            count++;
                        }
                    }
                }
                
                // Calculate the average and store it in the result matrix.
                // Integer division floors the result.
                result[i][j] = sum / count;
            }
        }
        
        return result;
    }
}

Image Smoother in C++

class Solution {
public:
    vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
        int m = img.size();
        int n = img[0].size();
        
        // Create a new matrix to store the smoothed image.
        vector<vector<int>> result(m, vector<int>(n, 0));
        
        // Iterate over each cell of the image.
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int sum = 0;
                int count = 0;
                
                // Iterate over the 3x3 neighborhood of the cell (i, j).
                for (int ni = i - 1; ni <= i + 1; ++ni) {
                    for (int nj = j - 1; nj <= j + 1; ++nj) {
                        // Check if the neighbor is within the image boundaries.
                        if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                            sum += img[ni][nj];
                            count++;
                        }
                    }
                }
                
                // Calculate the average and store it in the result matrix.
                // Integer division floors the result.
                result[i][j] = sum / count;
            }
        }
        
        return result;
    }
};

Image Smoother in TypeScript

function imageSmoother(img: number[][]): number[][] {
    const m = img.length;
    const n = img[0].length;

    // Create a new matrix to store the smoothed image.
    const result: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));

    // Iterate over each cell of the image.
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            let sum = 0;
            let count = 0;

            // Iterate over the 3x3 neighborhood of the cell (i, j).
            for (let ni = i - 1; ni <= i + 1; ni++) {
                for (let nj = j - 1; nj <= j + 1; nj++) {
                    // Check if the neighbor is within the image boundaries.
                    if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                        sum += img[ni][nj];
                        count++;
                    }
                }
            }

            // Calculate the average and store it in the result matrix.
            // Math.floor is needed as division in JS produces floats.
            result[i][j] = Math.floor(sum / count);
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.