Largest Local Values in a Matrix - Complete Solution Guide
Largest Local Values in a Matrix is LeetCode problem 2373, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 . 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 ma
Detailed Explanation
The problem asks you to find the largest value within each 3x3 submatrix of a given square matrix (n x n). The input is an n x n integer matrix `grid`. The output is an (n-2) x (n-2) matrix `maxLocal`, where each element `maxLocal[i][j]` represents the maximum value found in the 3x3 submatrix centered at `grid[i+1][j+1]`. The problem emphasizes that the submatrices are always 3x3 and contiguous within the larger matrix. Constraints limit the size of the input matrix (3 ≤ n ≤ 100) and the range of values within the matrix (1 ≤ grid[i][j] ≤ 100).
Solution Approach
The provided solutions use a brute-force approach. They iterate through each possible 3x3 submatrix within the input grid. For each submatrix, they find the maximum value among its nine elements and store this maximum value in the corresponding position in the output matrix `maxLocal`. This approach is straightforward and easy to understand.
Step-by-Step Algorithm
- Initialize an (n-2) x (n-2) matrix `maxLocal` to store the results.
- Iterate through each possible starting row index `i` from 0 to n-3.
- For each `i`, iterate through each possible starting column index `j` from 0 to n-3.
- For each `(i, j)` pair, iterate through the 3x3 submatrix centered at `grid[i+1][j+1]`, finding the maximum value.
- Store the maximum value found in step 4 at `maxLocal[i][j]`.
- Return the `maxLocal` matrix.
Key Insights
- The problem can be solved efficiently using nested loops to iterate through all possible 3x3 submatrices.
- No sophisticated data structures are needed; simple nested loops and a `max` function are sufficient.
- The output matrix will always be smaller than the input matrix by a border of one row and one column on each side, because 3x3 submatrices can't be formed at the edges.
Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Topics
This problem involves: Array, Matrix.
Companies
Asked at: OpenAI.