Largest Local Values in a Matrix - Problem

Imagine you're analyzing satellite imagery and need to identify hotspots in a grid-based map. Given an n x n integer matrix grid, your task is to find the maximum value in every possible 3x3 neighborhood.

Create a matrix maxLocal of size (n-2) x (n-2) where each element maxLocal[i][j] represents the largest value found in the 3x3 submatrix centered at position (i+1, j+1) in the original grid.

Visual Example:

Original 4x4 grid:    Result 2x2 grid:
[9,9,8,1]              [9,9]
[5,6,2,6]       โ†’      [8,6]
[8,2,6,4]
[6,2,2,2]

Each value in the result represents the maximum of a 3x3 region from the original matrix.

Input & Output

example_1.py โ€” Basic 4x4 Grid
$ Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
โ€บ Output: [[9,9],[8,6]]
๐Ÿ’ก Note: First 3x3 region (top-left): max of [9,9,8,5,6,2,8,2,6] = 9. Second 3x3 region (top-right): max of [9,8,1,6,2,6,2,6,4] = 9. Third 3x3 region (bottom-left): max of [5,6,2,8,2,6,6,2,2] = 8. Fourth 3x3 region (bottom-right): max of [6,2,6,2,6,4,2,2,2] = 6.
example_2.py โ€” Minimum Size Grid
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
โ€บ Output: [[1]]
๐Ÿ’ก Note: For a 3x3 input, we get a 1x1 output. The only 3x3 region is the entire grid, and the maximum value is 1.
example_3.py โ€” Larger Grid with Pattern
$ Input: grid = [[20,8,20,6,16],[8,16,4,12,8],[20,4,20,10,12],[8,12,8,16,4],[16,8,12,4,20]]
โ€บ Output: [[20,20,16],[20,20,12],[20,16,16]]
๐Ÿ’ก Note: Each position in the result corresponds to the maximum value found in the respective 3x3 region of the original 5x5 grid.

Constraints

  • n == grid.length == grid[i].length
  • 3 โ‰ค n โ‰ค 100
  • 1 โ‰ค grid[i][j] โ‰ค 100

Visualization

Tap to expand
Original Matrix (4ร—4)9981562682646222Current 3ร—3 WindowResult Matrix (2ร—2)9986Max = 9Step 1: Finding maximum in first 3ร—3 region
Understanding the Visualization
1
Initialize Result Matrix
Create a (n-2) ร— (n-2) matrix to store maximum values
2
Position Sliding Window
Place 3x3 window at each valid position (0,0) to (n-3,n-3)
3
Find Local Maximum
Scan all 9 cells in current window to find maximum value
4
Store Result
Place the maximum value in corresponding position of result matrix
Key Takeaway
๐ŸŽฏ Key Insight: By systematically scanning each valid 3ร—3 region and tracking the maximum value, we can efficiently build the result matrix in O(nยฒ) time complexity.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~8 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen