Equal Sum Grid Partition I - Problem
Equal Sum Grid Partition

Imagine you're a data analyst working with a financial spreadsheet filled with positive transaction amounts. Your task is to determine if you can make exactly one cut - either horizontal (splitting rows) or vertical (splitting columns) - such that the sum of numbers on both sides of the cut is perfectly balanced.

Given an m × n matrix grid of positive integers, return true if such a partition exists, otherwise return false.

Key Requirements:
• Make exactly one cut (horizontal OR vertical, not both)
• Both resulting sections must be non-empty
• The sum of elements in both sections must be equal

Example: In a 3×3 grid, a vertical cut between columns 1 and 2 creates a left section (column 0) and right section (columns 1-2). If their sums are equal, return true!

Input & Output

example_1.py — Basic Equal Partition
$ Input: grid = [[1,1,1,1],[1,1,1,1],[1,1,1,1]]
Output: true
💡 Note: A vertical cut between columns 1 and 2 creates left section with sum 6 (2 columns × 3 rows × 1) and right section with sum 6 (2 columns × 3 rows × 1). Since 6 = 6, return true.
example_2.py — No Valid Partition
$ Input: grid = [[1,2],[3,4]]
Output: false
💡 Note: Total sum = 10. Horizontal cut: top=3, bottom=7 (3≠7). Vertical cut: left=4, right=6 (4≠6). No cut creates equal partitions.
example_3.py — Single Row Matrix
$ Input: grid = [[2,4,2,8]]
Output: true
💡 Note: Only vertical cuts possible. Cut between columns 1 and 2: left=[2,4]=6, right=[2,8]=10 (no). Cut between columns 2 and 3: left=[2,4,2]=8, right=[8]=8. Since 8=8, return true.

Visualization

Tap to expand
LEFTRIGHTPerfect Break PointSum = 150 calSum = 150 cal
Understanding the Visualization
1
Check Total Calories
Count all calories - if odd number, impossible to split equally
2
Try Horizontal Breaks
Test breaking between each row, using running total of calories above the break
3
Try Vertical Breaks
Test breaking between each column, using running total of calories to the left
4
Find Equal Split
When running total equals exactly half the total calories, we found our break point!
Key Takeaway
🎯 Key Insight: Use running sums instead of recalculating from scratch - this reduces time complexity from O(m²n + mn²) to O(mn)

Time & Space Complexity

Time Complexity
⏱️
O(mn)

O(mn) to calculate total sum and prefix sums + O(m+n) to check all cut positions

n
2n
Linear Growth
Space Complexity
O(m+n)

O(m) for row prefix sums + O(n) for column prefix sums

n
2n
Linearithmic Space

Constraints

  • 1 ≤ m, n ≤ 1000
  • 1 ≤ grid[i][j] ≤ 106
  • Matrix contains only positive integers
  • Both resulting sections after cut must be non-empty
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
28.5K Views
Medium Frequency
~18 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen