#3548

Equal Sum Grid Partition II

Hard
ArrayHash TableMatrixEnumerationPrefix 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)

Instead of checking all cuts, we can calculate prefix sums for rows and columns, allowing us to efficiently determine the sums of sections and check for possible discounts.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate total sum of the grid and prefix sums for rows and columns.
  2. 2Step 2: For each possible cut, check if the sums are equal or can be made equal by removing one cell.
  3. 3Step 3: Use a frequency map to track cell values for quick lookup.
solution.py16 lines
1def canPartition(grid):
2    total = sum(sum(row) for row in grid)
3    m, n = len(grid), len(grid[0])
4    row_sums = [sum(row) for row in grid]
5    col_sums = [sum(grid[i][j] for i in range(m)) for j in range(n)]
6    for i in range(m-1):
7        top_sum = sum(row_sums[:i+1])
8        bottom_sum = total - top_sum
9        if top_sum == bottom_sum or abs(top_sum - bottom_sum) <= max(max(row) for row in grid):
10            return True
11    for j in range(n-1):
12        left_sum = sum(col_sums[:j+1])
13        right_sum = total - left_sum
14        if left_sum == right_sum or abs(left_sum - right_sum) <= max(max(row) for row in grid):
15            return True
16    return False

Complexity note: We compute prefix sums in linear time, allowing us to check conditions efficiently, leading to O(n) complexity.

  • 1Prefix sums help in reducing redundant calculations.
  • 2Checking for possible discounts can be done efficiently with frequency maps.

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