#3546

Equal Sum Grid Partition I

Medium
ArrayMatrixEnumerationPrefix SumHash MapArray
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)

Use prefix sums to efficiently calculate section sums. This allows us to determine if a cut can yield equal sums in linear time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total sum of the grid and check if it's even.
  2. 2Step 2: Compute prefix sums for rows and check for horizontal cuts.
  3. 3Step 3: Compute prefix sums for columns and check for vertical cuts.
solution.py16 lines
1def canPartition(grid):
2    total_sum = sum(sum(row) for row in grid)
3    if total_sum % 2 != 0:
4        return False
5    target = total_sum // 2
6    prefix_sum = 0
7    for r in range(len(grid) - 1):
8        prefix_sum += sum(grid[r])
9        if prefix_sum == target:
10            return True
11    prefix_sum = 0
12    for c in range(len(grid[0]) - 1):
13        prefix_sum += sum(grid[i][c] for i in range(len(grid)))
14        if prefix_sum == target:
15            return True
16    return False

Complexity note: The complexity is linear due to the single pass needed for prefix sums.

  • 1Total sum must be even for equal partition.
  • 2Prefix sums allow efficient sum calculations.

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