#661
Image Smoother
EasyArrayMatrixMatrix TraversalSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(m * n) |
| Space | O(m * n) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
The optimal approach is similar to the brute force but focuses on minimizing redundant calculations by using a single pass to compute the sum and count of valid neighbors. This reduces the number of iterations needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a new matrix of the same size to store the smoothed values.
- 2Step 2: For each pixel, calculate the total and count of valid neighbors in a single nested loop.
- 3Step 3: Store the computed average in the new matrix after processing all pixels.
solution.py16 lines
1# Full working Python code
2
3def imageSmoother(img):
4 m, n = len(img), len(img[0])
5 result = [[0] * n for _ in range(m)]
6 for i in range(m):
7 for j in range(n):
8 total, count = 0, 0
9 for di in range(-1, 2):
10 for dj in range(-1, 2):
11 ni, nj = i + di, j + dj
12 if 0 <= ni < m and 0 <= nj < n:
13 total += img[ni][nj]
14 count += 1
15 result[i][j] = total // count
16 return resultℹ
Complexity note: The time complexity remains O(m * n) as we still process each pixel, but we ensure each pixel's neighbors are counted efficiently. Space complexity is O(m * n) for the result matrix.
- 1Understanding how to handle edge cases (corners and edges) is crucial.
- 2Recognizing that the average should only consider valid neighboring cells can help simplify the logic.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.