↓Skip to main content
  1. LeetCode/

LeetCode 1292: Maximum Side Length of a Square with Sum Less than or Equal to Threshold

·3 mins· ·
LeetCode Medium Binary-Search Prefix-Sum Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-08-30

  • Submissions: Accepted → Wrong Answer (changed the loop condition)

Approach
#

  1. 2D prefix sums: P[i][j] is the sum from (0, 0) to (i-1, j-1), so any square sum takes O(1).
  2. Binary search on the side length: all values are non-negative, so if a square of side L fits, any side L - 1 square inside it has no larger sum, so L - 1 fits too. The condition is monotonic.

check(L) scans every bottom-right corner for a side-L square with sum <= threshold, in O(mn).

My Attempt: changing the loop condition but not the updates
#

The first submission passed with the closed style:

while left <= right:
    ...
    if valid:
        left = mid + 1
    else:
        right = mid - 1

Later I switched to while left < right but kept right = mid - 1. The half-open style needs hi = mid; mixing the two skips the answer, hence the WA.

Solution
#

Using the “find the largest feasible value” form: find the first infeasible side length and subtract 1.

class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        m, n = len(mat), len(mat[0])
        P = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m):
            for j in range(n):
                P[i + 1][j + 1] = P[i][j + 1] + P[i + 1][j] - P[i][j] + mat[i][j]

        def ok(L: int) -> bool:
            for i in range(L, m + 1):
                for j in range(L, n + 1):
                    if P[i][j] - P[i - L][j] - P[i][j - L] + P[i - L][j - L] <= threshold:
                        return True
            return False

        lo, hi = 1, min(m, n) + 1          # first infeasible side length
        while lo < hi:
            mid = (lo + hi) // 2
            if ok(mid):
                lo = mid + 1
            else:
                hi = mid
        return lo - 1

ok returns as soon as it finds a fitting square instead of scanning everything.

Complexity
#

Time O(mn log(min(m, n))), space O(mn).

Mistakes to Avoid
#

  • Mixing the two binary search styles: changing the loop condition but not the updates.
  • Getting the 2D prefix arithmetic wrong: P[i][j] - P[i-L][j] - P[i][j-L] + P[i-L][j-L], adding the last term back.
  • Forgetting the answer can be 0: return 0 when even side 1 does not fit.

Interview Explanation
#

I build 2D prefix sums so any square sum is O(1). Since values are non-negative, if side L fits then smaller sides fit, so I binary search the side length; check scans every bottom-right corner and returns as soon as some square’s sum is within the threshold. I use the “first infeasible side minus 1” form. Time O(mn log(min(m, n))).

Related

LeetCode 1712: Ways to Split Array Into Three Subarrays
·4 mins
LeetCode Medium Binary-Search Prefix-Sum Two-Pointers
LeetCode 1712 note: fix the first cut and find the valid range of the second cut with two bisects or two monotonic pointers
LeetCode 3814: Maximum Capacity Within Budget
·2 mins
LeetCode Medium Binary-Search Sorting Prefix-Sum
LeetCode 3814 note: sort by cost with a prefix maximum of capacity, and bisect the most expensive partner for each machine
LeetCode 3413: Maximum Coins From K Consecutive Bags
·3 mins
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 3413 note: the best k bags always have one end on a segment boundary; compute “left end at a segment start” and “right end at a segment end” (the latter by mirroring and reusing the same function)
LeetCode 2838: Maximum Coins Heroes Can Collect
·2 mins
LeetCode Medium Binary-Search Prefix-Sum Sorting
LeetCode 2838 note: sort monsters by power, build coin prefix sums, and bisect_right per hero
LeetCode 1838: Frequency of the Most Frequent Element
·2 mins
LeetCode Medium Sliding-Window Sorting Greedy Prefix-Sum Binary-Search Array
LeetCode 1838 note: after sorting, raising the whole window to nums[right] costs nums[right] × length − window sum; shrink the left while that exceeds k
LeetCode 2271: Maximum White Tiles Covered by a Carpet
·2 mins
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 2271 note: starting the carpet at some segment’s start is never worse; after sorting, two pointers sum the fully covered segments and count the last one partially