Python coding

Sub-rectangles that sum to a target

Given a grid of integers grid (at least one row and one column; values may be negative) and an integer target, count the sub-rectangles whose cells add up to exactly target. A sub-rectangle is the block of cells from row r1 to r2 and column c1 to c2, all four bounds included; two sub-rectangles are different when any bound differs.

With r rows and c columns, trying every rectangle is O(r²c²). Aim for O(r²c), or O(c²r) when the grid has more rows than columns.

Besides the tests, one large input (an 8 × 720 grid) with a ~220 ms limit (scaled to your device's speed): brute force won't pass.

  • count_target_rects([[1,0,1],[0,-1,0]], 0) → 5
  • count_target_rects([[2,-1],[-1,2]], 1) → 4
  • count_target_rects([[2,1,3],[1,2,0]], 3) → 7
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Fix a top row and a bottom row. The cells between them squash into one list of column sums, and each rectangle with those rows is a contiguous run of that list.

Hint 2

Count the runs of that list that sum to target the 1D way: running prefix sums and a map of how often each value appeared, seeded with {0: 1}.

Hint 3

Grow bottom one row at a time and add that row into the column sums, so each pair of rows costs O(c). If there are more rows than columns, transpose the grid first.

Solution and why it works
pythonO(r²c) with r ≤ c (the shorter side is paired) · O(c), plus O(r · c) for the transposed copy
def count_target_rects(grid: list[list[int]], target: int) -> int:
    if len(grid) > len(grid[0]):
        grid = [list(col) for col in zip(*grid)]   # pair up the shorter side
    rows, cols = len(grid), len(grid[0])
    total = 0
    for top in range(rows):
        col_sums = [0] * cols                      # column sums of rows top..bottom
        for bottom in range(top, rows):
            row = grid[bottom]
            counts, prefix = {0: 1}, 0
            for c in range(cols):                  # 1D: runs of col_sums that hit target
                col_sums[c] += row[c]
                prefix += col_sums[c]
                total += counts.get(prefix - target, 0)
                counts[prefix] = counts.get(prefix, 0) + 1
    return total

Fixing top and bottom rows turns the grid into one list of column sums, and every rectangle on those rows is a run of it. Counting runs that sum to target is the 1D move: prefix sums and a map of how often each appeared, seeded with {0: 1}. Growing bottom row by row updates the sums in O(c), for O(r²c) in total; transpose if rows outnumber columns. The trap: a 2D prefix table sums one rectangle in O(1), but there are O(r²c²) of them.