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 in a Matrix INPUT 4x4 Matrix Grid 9 9 8 1 5 6 2 6 8 2 6 4 6 2 2 2 grid = [ [9,9,8,1], [5,6,2,6], [8,2,6,4], [6,2,2,2] ] n = 4, Output: (n-2)x(n-2) = 2x2 ALGORITHM STEPS 1 Find 3x3 at (0,0) Max of [9,9,8,5,6,2,8,2,6] 9 9 8 5 6 2 8 2 6 = 9 2 Find 3x3 at (0,1) Max of [9,8,1,6,2,6,2,6,4] = 9 3 Find 3x3 at (1,0) Max of [5,6,2,8,2,6,6,2,2] = 8 4 Find 3x3 at (1,1) Max of [6,2,6,2,6,4,2,2,2] = 6 for i in 0 to n-3: for j in 0 to n-3: find max Sliding 3x3 window approach FINAL RESULT 2x2 Output Matrix (maxLocal) 9 9 8 6 [0][0] [0][1] [1][0] [1][1] Output: [[9,9],[8,6]] OK - Correct Key Insight: The optimized single pass approach slides a 3x3 window across the grid. For each position (i,j) in the output matrix, we find the maximum of 9 elements centered at grid[i+1][j+1]. Time: O((n-2)^2 * 9) = O(n^2) TutorialsPoint - Largest Local Values in a Matrix | Optimized Single Pass Approach
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