Largest Local Values in a Matrix - Problem

You are given an n x n integer matrix grid.

Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:

  • maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.

In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.

Return the generated matrix.

Input & Output

Example 1 — 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: For position (0,0): 3x3 window has max value 9. For position (0,1): 3x3 window has max value 9. For position (1,0): 3x3 window has max value 8. For position (1,1): 3x3 window has max value 6.
Example 2 — Minimum 3x3 Grid
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: [[1]]
💡 Note: Only one 3x3 window possible, and the maximum value in all 1s is 1.
Example 3 — Larger Grid with Negatives
$ Input: grid = [[-1,2,-3],[4,-5,6],[-7,8,-9]]
Output: [[8]]
💡 Note: The single 3x3 window contains all elements, and the maximum is 8.

Constraints

  • n == grid.length == grid[i].length
  • 3 ≤ n ≤ 100
  • 1 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Largest Local Values: Transform 4x4 → 2x2Original 4x4 Grid9981562682646222Window 1: Max = 9Extract MaxResult 2x2 Grid9986Each result cell = maximum of corresponding 3x3 windowOutput size: (n-2) × (n-2) = 2 × 2
Understanding the Visualization
1
Input Grid
4x4 matrix with integer values
2
Extract Windows
Find all possible 3x3 submatrices
3
Find Maximums
Calculate maximum for each 3x3 window
Key Takeaway
🎯 Key Insight: The problem is essentially applying a 3x3 maximum filter to the matrix, reducing dimensions by 2 in each direction
Asked in
Google 45 Amazon 35 Microsoft 28 Apple 22
89.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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