#1292

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

Medium
ArrayBinary SearchMatrixPrefix SumPrefix SumMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

Using prefix sums allows us to quickly calculate the sum of any square in constant time, making our solution much faster.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a prefix sum matrix where each cell (i, j) contains the sum of elements from (0,0) to (i,j).
  2. 2Step 2: Iterate through possible square sizes and check if the sum of each square can be computed using the prefix sum matrix.
  3. 3Step 3: If the sum of the square is less than or equal to the threshold, update the maximum side length.
solution.py17 lines
1# Full working Python code
2
3def maxSideLength(mat, threshold):
4    m, n = len(mat), len(mat[0])
5    prefix_sum = [[0] * (n + 1) for _ in range(m + 1)]
6    for i in range(1, m + 1):
7        for j in range(1, n + 1):
8            prefix_sum[i][j] = mat[i - 1][j - 1] + prefix_sum[i - 1][j] + prefix_sum[i][j - 1] - prefix_sum[i - 1][j - 1]
9    max_length = 0
10    for length in range(1, min(m, n) + 1):
11        for i in range(length, m + 1):
12            for j in range(length, n + 1):
13                square_sum = prefix_sum[i][j] - prefix_sum[i - length][j] - prefix_sum[i][j - length] + prefix_sum[i - length][j - length]
14                if square_sum <= threshold:
15                    max_length = max(max_length, length)
16    return max_length
17

Complexity note: The time complexity is O(n²) due to iterating through the prefix sums for each square size. The space complexity is O(n²) because we store the prefix sums in a separate matrix.

  • 1Using prefix sums allows for quick sum calculations of submatrices.
  • 2Iterating through possible square sizes systematically helps ensure we find the maximum.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.