Equal Sum Grid Partition I Problem
#3546
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3546.
You are given an m x n matrix grid of positive integers. Your task is to determine if it is possible to make either one horizontal or one vertical cut on the grid such that:
- Each of the two resulting sections formed by the cut is non-empty.
- The sum of the elements in both sections is equal.
Return true if such a partition exists; otherwise return false.
Example 1:
Input: grid = [[1,4],[2,3]]
Output: true
Explanation:


A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is true.
Example 2:
Input: grid = [[1,3],[2,4]]
Output: false
Explanation:
No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is false.
Constraints:
1 <= m == grid.length <= 10^51 <= n == grid[i].length <= 10^52 <= m * n <= 10^51 <= grid[i][j] <= 10^5
Solution
Approach: Prefix Sums over Cut Lines
Compute the total sum s of the grid. If s is odd, two equal halves are impossible, so return false.
Otherwise try every cut line:
- Horizontal cuts: go through the rows from the top, adding each row's sum to a running total
pre. Ifpre * 2 == sand the current row is not the last one, cutting right below it gives two equal parts. - Vertical cuts: do the same column by column from the left.
If no cut works, return false.
Complexity: O(m * n) time and O(1) extra space.
class Solution:
def canPartitionGrid(self, grid: List[List[int]]) -> bool:
s = sum(sum(row) for row in grid)
if s % 2:
return False
pre = 0
for i, row in enumerate(grid):
pre += sum(row)
if pre * 2 == s and i != len(grid) - 1:
return True
pre = 0
for j, col in enumerate(zip(*grid)):
pre += sum(col)
if pre * 2 == s and j != len(grid[0]) - 1:
return True
return False