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

A square is defined as a submatrix where all sides have equal length. The sum of a square is the sum of all elements within that submatrix.

Input & Output

Example 1 — Basic Case
$ 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 position (0,0) has sum = 1+1+1+1 = 4.
Example 2 — Larger Threshold
$ Input: mat = [[2,2,2,2,5,5],[2,2,2,2,5,5],[2,2,2,2,5,5],[2,2,2,2,5,5]], threshold = 18
Output: 2
💡 Note: A 2×2 square of all 2's has sum = 8 ≤ 18. A 3×3 square would have sum ≥ 18, but we need strictly ≤ threshold.
Example 3 — No Valid Square
$ Input: mat = [[1,1,1,1],[1,1,1,1],[1,1,1,1]], threshold = 0
Output: 0
💡 Note: Even the smallest 1×1 square has sum = 1 > 0, so no valid square exists.

Constraints

  • 1 ≤ m, n ≤ 300
  • 0 ≤ mat[i][j] ≤ 104
  • 0 ≤ threshold ≤ 105

Visualization

Tap to expand
Maximum Square with Sum ≤ Threshold INPUT Matrix (3x7): 1 1 3 2 4 3 2 1 1 3 2 4 3 2 1 1 3 2 4 3 2 threshold = 4 Example Squares: 1 1x1: sum=1 1 1 1 1 2x2: sum=4 OK! 3x3 sum > 4 ALGORITHM STEPS 1 Build Prefix Sum Create 2D prefix sum matrix prefix[i][j] = sum of all mat[0..i][0..j] 2 Binary Search Search for max side length lo=1, hi=min(m,n)=3 3 Check Each Square For each position (i,j) sum = p[i][j] - p[i-k][j] - p[i][j-k] + p[i-k][j-k] 4 Validate Threshold sum <= threshold ? Yes: expand No: shrink FINAL RESULT Maximum valid square found: 1 1 3 2 4 3 2 1 1 3 2 4 3 2 1 1 3 2 4 3 2 Square Sum Calculation: 1 + 1 + 1 + 1 = 4 4 <= 4 (threshold) Condition satisfied! Output: 2 Max side length = 2 No 3x3 square has sum <= 4 Key Insight: Use 2D prefix sums to compute any square's sum in O(1) time. Combined with binary search on the side length, we achieve O(mn * log(min(m,n))) time complexity. The prefix sum formula prefix[i][j] - prefix[i-k][j] - prefix[i][j-k] + prefix[i-k][j-k] gives the sum of any k*k square. TutorialsPoint - Maximum Side Length of a Square with Sum Less than or Equal to Threshold | Optimal Solution
Asked in
Google 35 Amazon 28 Facebook 22
32.0K Views
Medium Frequency
~25 min Avg. Time
856 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