#2373

Largest Local Values in a Matrix

Easy
ArrayMatrixSliding WindowMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

While the brute force approach is simple, we can optimize it by using a sliding window technique to keep track of the maximum values more efficiently. This reduces the number of redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a new matrix `maxLocal` of size (n-2) x (n-2).
  2. 2Step 2: Loop through the grid starting from index 1 to n-2 for both rows and columns.
  3. 3Step 3: For each position, calculate the maximum of the 3x3 submatrix using a sliding window approach, updating the maximum as we move through the grid.
solution.py13 lines
1# Full working Python code
2
3def largestLocal(grid):
4    n = len(grid)
5    maxLocal = [[0] * (n - 2) for _ in range(n - 2)]
6    for i in range(1, n - 1):
7        for j in range(1, n - 1):
8            maxLocal[i - 1][j - 1] = max(
9                grid[i - 1][j - 1], grid[i - 1][j], grid[i - 1][j + 1],
10                grid[i][j - 1], grid[i][j], grid[i][j + 1],
11                grid[i + 1][j - 1], grid[i + 1][j], grid[i + 1][j + 1]
12            )
13    return maxLocal

Complexity note: The time complexity remains O(n²) as we still iterate through the grid, but we reduce the number of comparisons by directly accessing the relevant elements instead of looping through them. The space complexity is O(1) since we only use the output matrix.

  • 1Understanding how to efficiently navigate through a matrix is crucial.
  • 2Recognizing patterns in submatrices can lead to optimized solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.