You are given an n x n
integer matrix grid
. Generate an n-2 x n-2
integer matrix result
such that:
result[i][j]
is equal to the largest value in the 3x3 matrix defined as follows:
(i, j)
Return the result
matrix.
Example:
Input: grid = [
[9, 9, 8, 1],
[5, 6, 2, 6],
[8, 2, 6, 4],
[6, 2, 2, 2]
]
Output: [
[9, 9],
[8, 6]
]
n
? (Minimum and Maximum values of n
)grid
? (Minimum and Maximum values of each element)n
is less than 3?n
is less than 3 because an n x n
grid where n < 3
cannot form even a single 3x3 subgrid. In such a case, output should be an empty list.result
of size n-2 x n-2
.result
matrix.result
matrix.The time complexity of this solution will be O(n^2), where n
is the dimension of the original grid. This is because:
n-2
times.Here’s the Python code to solve the problem:
def largestLocal(grid):
n = len(grid)
if n < 3:
return []
result = [[0] * (n - 2) for _ in range(n - 2)]
for i in range(n - 2):
for j in range(n - 2):
max_val = -float('inf')
for k in range(3):
for l in range(3):
max_val = max(max_val, grid[i + k][j + l])
result[i][j] = max_val
return result
# Example usage:
grid = [
[9, 9, 8, 1],
[5, 6, 2, 6],
[8, 2, 6, 4],
[6, 2, 2, 2]
]
print(largestLocal(grid)) # Output: [[9, 9], [8, 6]]
This code will correctly compute the largest local values in a matrix as described by the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?