Maximum Side Length of a Square with Sum Less than or Equal to Threshold Problem
Description
LeetCode Problem 1292.
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 to threshold or return 0 if there is no such square.
Example 1:

Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than or equal to 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 3000 <= mat[i][j] <= 10^40 <= threshold <= 10^5
Solution
Approach: 2D Prefix Sums and Binary Search on the Side
First build a 2D prefix sum: pre[i][j] is the sum of the top-left block mat[0..i-1][0..j-1]. Then the sum of the k x k square whose top-left cell is (i, j) takes O(1):
pre[i + k][j + k] - pre[i][j + k] - pre[i + k][j] + pre[i][j]
Checking whether some k x k square fits under the threshold therefore costs O(mn): try every top-left corner.
The values are non-negative, so if a square of side k fits, the (k - 1) x (k - 1) square in its corner fits too (its sum can only be smaller). The property "side k fits" is monotone, which lets us binary search for the largest k between 0 and min(m, n). Side 0 always counts as fitting, which is how the answer becomes 0 when every single cell already exceeds the threshold (Example 2).
Complexity: O(mn · log(min(m, n))) time and O(mn) space for the prefix sums.
class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
m, n = len(mat), len(mat[0])
# pre[i][j] = sum of mat[0..i-1][0..j-1]
pre = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
pre[i + 1][j + 1] = pre[i][j + 1] + pre[i + 1][j] - pre[i][j] + mat[i][j]
def fits(k): # is there a k x k square with sum <= threshold?
for i in range(m - k + 1):
for j in range(n - k + 1):
if pre[i + k][j + k] - pre[i][j + k] - pre[i + k][j] + pre[i][j] <= threshold:
return True
return False
# Entries are non-negative, so if side k fits, every smaller side fits too.
lo, hi = 0, min(m, n)
while lo < hi:
mid = (lo + hi + 1) // 2
if fits(mid):
lo = mid
else:
hi = mid - 1
return lo