Problem
Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal tothreshold or return0 if there is no such square.
Examples
Example 1
| |
Example 2
| |
Constraints
m == mat.lengthn == mat[i].length1 <= m, n <= 3000 <= mat[i][j] <= 10^40 <= threshold <= 10^5
Solution
Method 1 – Binary Search with 2D Prefix Sum
Intuition
To efficiently check if a square of a given side length has a sum less than or equal to the threshold, we use a 2D prefix sum. We then binary search on the possible side lengths to find the largest valid one.
Approach
- Compute a 2D prefix sum for the matrix to allow O(1) sum queries for any submatrix.
- Use binary search on the possible side lengths (from 0 to min(m, n)).
- For each candidate side length, check all possible top-left corners to see if any square of that size has a sum ≤ threshold.
- If such a square exists, try a larger size; otherwise, try smaller.
- Return the largest valid side length found.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(m n log(min(m, n))), wheremandnare the matrix dimensions. Each binary search step checks all possible squares. - 🧺 Space complexity:
O(m n), for the prefix sum matrix.