09 Sept 2026Go / Python / TypeScriptEasy

Image Smoother

Replace each image cell with the floor of the average over its valid neighboring cells.

For every cell, inspect the bounded three-by-three neighborhood, accumulate its sum and count, and write the integer average to a new matrix.

complexity

O(rows * columns) time and O(rows * columns) output space.

solution files

  • Go image-smoother/solution.go
  • Python image-smoother/solution.py
  • TypeScript image-smoother/solution.ts

Solution files

Goimage-smoother/solution.go
package main

func imageSmoother(img [][]int) [][]int {
	rows, columns := len(img), len(img[0])
	result := make([][]int, rows)
	for row := 0; row < rows; row++ {
		result[row] = make([]int, columns)
		for column := 0; column < columns; column++ {
			sum, count := 0, 0
			for r := maxInt(0, row-1); r <= minInt(rows-1, row+1); r++ {
				for c := maxInt(0, column-1); c <= minInt(columns-1, column+1); c++ {
					sum += img[r][c]
					count++
				}
			}
			result[row][column] = sum / count
		}
	}
	return result
}

func minInt(a int, b int) int {
	if a < b {
		return a
	}
	return b
}
func maxInt(a int, b int) int {
	if a > b {
		return a
	}
	return b
}
Pythonimage-smoother/solution.py
class Solution:
    def imageSmoother(self, img: list[list[int]]) -> list[list[int]]:
        rows, columns = len(img), len(img[class="syntax-number">0])
        result = [[class="syntax-number">0] * columns for _ in range(rows)]
        for row in range(rows):
            for column in range(columns):
                values = [img[r][c] for r in range(max(class="syntax-number">0, row - class="syntax-number">1), min(rows, row + class="syntax-number">2)) for c in range(max(class="syntax-number">0, column - class="syntax-number">1), min(columns, column + class="syntax-number">2))]
                result[row][column] = sum(values) class=class="syntax-string">"syntax-comment">// len(values)
        return result
TypeScriptimage-smoother/solution.ts
function imageSmoother(img: number[][]): number[][] {
  return img.map((row, r) => row.map((_, c) => {
    let sum = class="syntax-number">0;
    let count = class="syntax-number">0;
    for (let rr = Math.max(class="syntax-number">0, r - class="syntax-number">1); rr <= Math.min(img.length - class="syntax-number">1, r + class="syntax-number">1); rr += class="syntax-number">1) {
      for (let cc = Math.max(class="syntax-number">0, c - class="syntax-number">1); cc <= Math.min(row.length - class="syntax-number">1, c + class="syntax-number">1); cc += class="syntax-number">1) { sum += img[rr][cc]; count += class="syntax-number">1; }
    }
    return Math.floor(sum / count);
  }));
}