Equal Sum Grid Partition II - 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 elements in both sections is equal, or can be made equal by discounting at most one single cell in total (from either section)
  • If a cell is discounted, the rest of the section must remain connected

Return true if such a partition exists; otherwise, return false.

Note: A section is connected if every cell in it can be reached from any other cell by moving up, down, left, or right through other cells in the section.

Input & Output

Example 1 — Vertical Cut with Cell Removal
$ Input: grid = [[1,1,1,1],[1,1,1,1]]
Output: true
💡 Note: Cut vertically between columns 1 and 2. Left sum = 4, right sum = 4. Already equal, so return true.
Example 2 — Horizontal Cut with Balancing
$ Input: grid = [[1,2],[3,4]]
Output: true
💡 Note: Cut horizontally between rows. Top sum = 3, bottom sum = 7. Remove cell with value 4, making bottom sum 3. Both sections remain connected.
Example 3 — No Valid Partition
$ Input: grid = [[1,1],[1,100]]
Output: false
💡 Note: No single horizontal or vertical cut can create balanced sections, even with one cell removal.

Constraints

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

Visualization

Tap to expand
INPUT GRID1234562x3 matrix withpositive integersALGORITHM STEPS1Try horizontal cuts2Try vertical cuts3Calculate section sums4Check if balancedVertical cut hereLeft: 1+4=5Right: 2+3+5+6=16Remove 6: Right becomes 10FINAL RESULTtrueValid partition foundwith cell removalKey Insight:Use prefix sums for O(1) range queries and systematically try all cuts with optional cell removalTutorialsPoint - Equal Sum Grid Partition II | Prefix Sum Optimization
Asked in
Google 15 Microsoft 12 Amazon 8
12.4K Views
Medium Frequency
~35 min Avg. Time
284 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