Python 0661.py
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
width = len(img[0])
height = len(img)
result = []
for y in range(height):
result.append([ None ] * width)
for y in range(height):
for x in range(width):
kernel = [ img[y][x] ]
if x > 0:
kernel.append(img[y][x-1])
if x > 0 and y > 0:
kernel.append(img[y-1][x-1])
if y > 0:
kernel.append(img[y-1][x])
if x < width-1 and y > 0:
kernel.append(img[y-1][x+1])
if x < width-1:
kernel.append(img[y][x+1])
if x < width-1 and y < height-1:
kernel.append(img[y+1][x+1])
if y < height-1:
kernel.append(img[y+1][x])
if y < height-1 and x > 0:
kernel.append(img[y+1][x-1])
result[y][x] = sum(kernel) // len(kernel)
return result
Difficulty
and has an acceptance rate of about 67% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method imageSmoother that receives a two-dimensional list img representing a grayscale image. The method returns a new image where each pixel value is replaced by the integer average of the pixel itself and its surrounding neighbors (up to eight adjacent cells). The algorithm walks the image row by row, builds a local kernel for each position, computes the average, and stores the result in a pre-allocated output matrix.
Initialization of Dimensions
The first step extracts the image dimensions:
width = len(img[0])
height = len(img)
These values are used throughout the routine to bound index checks and to allocate the result matrix.
Pre-allocation of the Result Matrix
Before any processing begins, the code creates a matrix of the same size as the input, filled with placeholder None values:
result = []
for y in range(height):
result.append([ None ] * width)
By allocating the full structure up front, the algorithm avoids repeated list growth operations inside the inner loop, which reduces overhead associated with dynamic resizing.
Iteration Over Pixels
The core of the algorithm consists of two nested loops that visit every coordinate (y, x):
for y in range(height):
for x in range(width):
...
The outer loop iterates over rows, while the inner loop processes each column within the current row.
Construction of the Neighborhood Kernel
For each pixel, a list named kernel is assembled containing the values of the pixel itself and any valid neighboring cells. The code uses a series of conditional checks to ensure that only existing neighbors are added, thereby handling border and corner cases gracefully.
kernel = [ img[y][x] ]
if x > 0:
kernel.append(img[y][x-1])
if x > 0 and y > 0:
kernel.append(img[y-1][x-1])
if y > 0:
kernel.append(img[y-1][x])
if x < width-1 and y > 0:
kernel.append(img[y-1][x+1])
if x < width-1:
kernel.append(img[y][x+1])
if x < width-1 and y < height-1:
kernel.append(img[y+1][x+1])
if y < height-1:
kernel.append(img[y+1][x])
if y < height-1 and x > 0:
kernel.append(img[y+1][x-1])
The conditional structure ensures that:
- Pixels on the left edge never attempt to read
x-1. - Pixels on the right edge never attempt to read
x+1. - Pixels on the top edge never attempt to read
y-1. - Pixels on the bottom edge never attempt to read
y+1. - Corners naturally receive only the three or four valid neighbors that exist.
Thus the algorithm correctly adapts to images of any size, including degenerate cases such as a single row, a single column, or a 1×1 image.
Averaging and Assignment
Once the kernel list is populated, the integer average is computed using floor division, which matches the problem’s requirement to truncate fractional parts:
result[y][x] = sum(kernel) // len(kernel)
The use of sum on a small, bounded list (maximum length nine) is efficient, and the integer division avoids the overhead of floating-point arithmetic.
Return of the Smoothed Image
After all pixels have been processed, the method returns the fully populated result matrix:
return result
Edge-Case Handling
The conditional checks around each neighbor addition guarantee that the algorithm never accesses an index outside the valid range. This includes:
- Top-left corner: only the pixel itself, the right neighbor, the bottom neighbor, and the bottom-right diagonal are considered.
- Top-right corner: only the pixel itself, the left neighbor, the bottom neighbor, and the bottom-left diagonal are considered.
- Bottom-left corner: only the pixel itself, the right neighbor, the top neighbor, and the top-right diagonal are considered.
- Bottom-right corner: only the pixel itself, the left neighbor, the top neighbor, and the top-left diagonal are considered.
- Single-row images: vertical neighbor checks (
y > 0andy < height-1) are always false, leaving only horizontal neighbors. - Single-column images: horizontal neighbor checks (
x > 0andx < width-1) are always false, leaving only vertical neighbors.
These safeguards make the function robust for any rectangular input.
Performance Optimizations Observed
The implementation includes several choices that improve runtime efficiency:
- Result matrix pre-allocation eliminates repeated list appends inside the inner loop, reducing memory allocation churn.
- Conditional neighbor inclusion builds the kernel with only the necessary elements, avoiding the creation of a fixed-size nine-element array that would later need to be filtered.
- Use of built-in
sumleverages a highly optimized C implementation for aggregating the kernel values. - Integer division (
//) avoids conversion to floating-point numbers, keeping the arithmetic in the integer domain and benefiting from faster CPU instructions. - Minimal variable scope: the kernel list is recreated for each pixel, allowing Python’s garbage collector to reclaim the short-lived list promptly, which helps keep memory usage predictable.
Overall, the code delivers a clear, direct solution that respects boundary conditions and employs straightforward optimizations to keep execution swift for typical image sizes.
ELI5 - Simplified Explanation
Imagine a big grid like a mosaic made of colorful square tiles. Each tile has a number on it that represents its color. Sometimes a picture looks a little bit too sharp or noisy, and the goal is to make it look smooth and soft.
To do this, the computer looks at every single tile one by one. For each tile, it reaches out to look at that tile and all the neighbors touching it, even the ones sitting diagonally in the corners. It puts all the numbers from that little cluster into a basket. Once all the neighboring numbers are in the basket, it adds them all up and shares that big total equally among all the tiles gathered. The result is a new, softer number that replaces the old one.
The process travels across the whole grid, starting from the top and moving row by row until every tile has been visited and softened. After visiting every spot and figuring out the new average, the final grid is ready, and the mosaic looks much smoother than before.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| haoel | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| haoel | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 693: Binary Number with Alternating Bits
- problem 762: Prime Number of Set Bits in Binary Representation
- problem 319: Bulb Switcher
- problem 2336: Smallest Number in Infinite Set
- problem 679: 24 Game
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality