Maximum Side Length of a Square with Sum Less than or Equal to Threshold - Problem

Imagine you're analyzing satellite images of farmland divided into a grid, where each cell represents the crop yield value for that area. You need to find the largest square region where the total crop yield doesn't exceed a given threshold.

Given an m x n matrix mat where each cell contains a non-negative integer, and an integer threshold, return the maximum side length of a square subregion whose sum is less than or equal to the threshold.

If no such square exists, return 0.

Example: In a 3×3 grid with threshold 4, a 2×2 square with sum 4 would be valid, but a 2×2 square with sum 5 would not be.

Input & Output

example_1.py — Basic Square
$ 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
💡 Note: The maximum side length of a square with sum ≤ 4 is 2. The 2×2 square at top-left has sum 1+1+1+1 = 4.
example_2.py — No Valid Square
$ Input: mat = [[2,2,2,2,5,5],[2,2,2,2,5,5],[2,2,2,2,5,5]], threshold = 1
Output: 0
💡 Note: No square (even 1×1) has sum ≤ 1 since all elements are ≥ 2.
example_3.py — Large Square Possible
$ Input: mat = [[1,1,1,1],[1,0,0,1],[1,0,0,1],[1,1,1,1]], threshold = 6
Output: 3
💡 Note: The 3×3 square starting at (0,1) has sum = 1+1+1+0+0+0+0+0+1 = 4 ≤ 6.

Constraints

  • 1 ≤ m, n ≤ 300
  • 0 ≤ mat[i][j] ≤ 104
  • 0 ≤ threshold ≤ 105
  • The matrix contains only non-negative integers

Visualization

Tap to expand
Original Matrix123456Prefix Sum Array13651221Binary Search1✓ Valid2✓ Valid3✗ InvalidAnswer: 2Key Insight: Binary Search + Prefix SumsTime: O(mn × log(min(m,n))) | Space: O(mn)
Understanding the Visualization
1
Build Cost Database
Create prefix sums to instantly calculate any rectangular area cost
2
Smart Size Search
Use binary search instead of checking every size linearly
3
Quick Validation
For each candidate size, check all positions using O(1) sum calculations
Key Takeaway
🎯 Key Insight: Binary search on the answer eliminates the need to check every possible square size, while prefix sums make range sum queries instant. This combination transforms an O(n⁵) brute force into an efficient O(mn log n) solution.
Asked in
Facebook 38 Google 25 Amazon 18 Microsoft 12
28.4K Views
Medium-High Frequency
~25 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen