Largest Local Values in a Matrix
EasyUpdated: Aug 2, 2025
Practice on:
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 the3 x 3matrix ingridcentered around rowi + 1and columnj + 1.
In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
Return the generated matrix.
Examples
Example 1:
Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
Output: [[9,9],[8,6]]
Explanation: The diagram above shows the original matrix and the generated matrix.
Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.
Example 2:
Input: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]
Output: [[2,2,2],[2,2,2],[2,2,2]]
Explanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.
Solution
Method 1 - Nested Loops with sliding window of 3x3 matrix
We create the 2 nested loops - 0 to n -2...which will fill the answer array. Now, we can run nested 3x3 loop to find max we have seen so far. These last 2 loops are like a sliding window
Video explanation
Here is the video explaining this method in detail. Please check it out:
<div class="youtube-embed"><iframe src="https://www.youtube.com/embed/P2nnzCljkvI" frameborder="0" allowfullscreen></iframe></div>
Code
Java
class Solution {
public int[][] largestLocal(int[][] grid) {
int n = grid.length;
int[][] ans = new int[n - 2][n - 2];
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < n - 2; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
ans[i][j] = Math.max(ans[i][j], grid[i + k][j + l]);
}
}
}
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n^2)- We run 2 outer loops with(n-2)x(n-2)complexity and 2 inner loops with3x3 = 9times the complexity. HenceO(9n^2) = O(n^2) - 🧺 Space complexity:
O(1)