Largest Local Values in a Matrix — LeetCode 2373 Python Solution

EasyArrayMatrix
Problem
#2373
Reading time
2 min

The 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.

Example

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.

Python solution

Python
class Solution:
    def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
        n = len(grid)
        ans = [[0] * (n - 2) for _ in range(n - 2)]
        for i in range(n - 2):
            for j in range(n - 2):
                ans[i][j] = max(
                    grid[x][y] for x in range(i, i + 3) for y in range(j, j + 3)
                )
        return ans

Complexity

MeasureComplexity
TimeO(m·n)
SpaceO(1) to O(m·n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2373. Largest Local Values in a Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2373. Largest Local Values in a Matrix?
LeetCode 2373. Largest Local Values in a Matrix is rated Easy on LeetCode.
What topics does LeetCode 2373. Largest Local Values in a Matrix cover?
LeetCode 2373. Largest Local Values in a Matrix is tagged Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview