Equal Sum Grid Partition I - Problem

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.

Input & Output

Example 1 — Equal Horizontal Partition
$ Input: grid = [[2,4],[2,4]]
Output: true
💡 Note: Horizontal cut after row 0: top section sum = 2+4 = 6, bottom section sum = 2+4 = 6. Both equal, so return true.
Example 2 — No Equal Partition
$ Input: grid = [[1,2],[3,4]]
Output: false
💡 Note: Total sum = 10. No horizontal or vertical cut creates equal partitions of 5 each.
Example 3 — Equal Vertical Partition
$ Input: grid = [[1,1],[1,1]]
Output: true
💡 Note: Horizontal cut after row 0: top section sum = 1+1 = 2, bottom section sum = 1+1 = 2. Both equal, so return true.

Constraints

  • 1 ≤ m, n ≤ 100
  • 1 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Equal Sum Grid Partition I INPUT 2x2 Grid Matrix 2 4 2 4 col 0 col 1 row 0 row 1 grid = [[2,4],[2,4]] Total Sum = 12 m=2, n=2 All positive integers ALGORITHM STEPS 1 Calculate Total Sum all elements: 2+4+2+4=12 2 Check if Divisible Target = 12/2 = 6 (OK) 3 Try Horizontal Cut Row 0 sum: 2+4 = 6 (OK) 2 4 2 4 CUT 4 Verify Both Parts Top=6, Bottom=6 (Equal!) Valid Partition Found! FINAL RESULT Horizontal Cut Solution 2 4 = 6 CUT 2 4 = 6 6 = 6 Output: true Partition exists! Both sections non-empty Sums are equal (6=6) Status: OK Key Insight: For a valid partition, total sum must be even. Then iterate through possible horizontal cuts (after each row) and vertical cuts (after each column). If cumulative sum equals half of total, a valid partition exists. Time: O(m*n), Space: O(1). Prefix sums enable efficient checking. TutorialsPoint - Equal Sum Grid Partition I | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
23.4K Views
Medium Frequency
~15 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