<p>Given a <code>m x n</code> matrix <code>mat</code> and an integer <code>threshold</code>, return <em>the maximum side-length of a square with a sum less than or equal to </em><code>threshold</code><em> or return </em><code>0</code><em> if there is no such square</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/12/05/e1.png" style="width: 335px; height: 186px;" />
<pre>
<strong>Input:</strong> mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum side length of square with sum less than 4 is 2 as shown.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> 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
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 300</code></li>
	<li><code>0 &lt;= mat[i][j] &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= threshold &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        m, n = len(mat), len(mat[0])

        # Build the prefix sum array
        prefix = self.build_prefix_sum(mat, m, n)

        # Perform binary search for the maximum valid side length
        lo, hi = 1, min(m, n)
        result = 0

        while lo <= hi:
            mid = (lo + hi) // 2
            if self.is_valid_square(prefix, m, n, mid, threshold):
                result = mid  # Valid side length found, try a larger one
                lo = mid + 1
            else:
                hi = mid - 1

        return result

    def build_prefix_sum(self, mat: List[List[int]], m: int, n: int) -> List[List[int]]:
        """
        Builds the prefix sum array for the matrix.
        """
        prefix = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m):
            for j in range(n):
                prefix[i + 1][j + 1] = prefix[i + 1][j] + prefix[i][j + 1] - prefix[i][j] + mat[i][j]
        return prefix

    def is_valid_square(self, prefix: List[List[int]], m: int, n: int, k: int, threshold: int) -> bool:
        """
        Checks if there exists a square submatrix of side length k with a sum <= threshold.
        """
        for i in range(m + 1 - k):
            for j in range(n + 1 - k):
                # Calculate the sum of the k x k submatrix using the prefix sum array
                submatrix_sum = (prefix[i + k][j + k] 
                                - prefix[i][j + k] 
                                - prefix[i + k][j] 
                                + prefix[i][j])
                if submatrix_sum <= threshold:
                    return True
        return False
22200