Find the Grid of Region Average - Problem
You're given an m x n grayscale image represented as a 2D grid where each cell contains a pixel intensity value between 0 and 255. Your task is to identify smooth regions within the image and calculate regional averages.
A region is defined as any 3 x 3 subgrid where adjacent pixels (sharing an edge) have intensity differences โค threshold. Think of this as finding areas where the image transitions are smooth enough to be considered uniform.
Key Rules:
- Each pixel can belong to multiple overlapping regions
- For pixels in multiple regions: average the floor values of each region's average
- For pixels in no regions: keep original intensity value
- Always use floor division for final results
Return the processed image where each pixel shows its regional average intensity.
Input & Output
example_1.py โ Basic Valid Region
$
Input:
image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3
โบ
Output:
[[9,9,9,10],[9,9,9,10],[9,9,9,10]]
๐ก Note:
The 3x3 region in the top-left corner has all adjacent pixels differing by โค 3, so all pixels in this region get the average value floor(81/9) = 9. The rightmost column pixels don't belong to any valid region, so they keep their original values.
example_2.py โ No Valid Regions
$
Input:
image = [[10,20,30],[15,25,35],[20,30,40]], threshold = 3
โบ
Output:
[[10,20,30],[15,25,35],[20,30,40]]
๐ก Note:
Adjacent pixels differ by more than threshold=3 (e.g., |10-20|=10 > 3), so no valid 3x3 regions exist. All pixels retain their original values.
example_3.py โ Multiple Overlapping Regions
$
Input:
image = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]], threshold = 0
โบ
Output:
[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
๐ก Note:
All pixels have the same value, so every 3x3 region is valid with average 1. Each pixel belongs to multiple regions, but all regions have the same average, so the result is unchanged.
Constraints
- 3 โค m, n โค 300
- 0 โค image[i][j] โค 255
- 0 โค threshold โค 255
- Adjacent pixels are those that share an edge (not diagonal)
- All averages should be calculated using floor division
Visualization
Tap to expand
Understanding the Visualization
1
Identify Smooth Regions
Find 3ร3 areas where adjacent pixels don't vary much (โค threshold)
2
Calculate Region Averages
Compute floor(sum/9) for each valid region
3
Handle Overlaps
Pixels in multiple regions get the average of all their region averages
4
Preserve Edges
Pixels not in any smooth region keep their original values
Key Takeaway
๐ฏ Key Insight: Pre-compute all valid regions once instead of revalidating them for each pixel - this transforms an O(mnร9) problem into O(mn) by eliminating redundant work.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code