Rectangular Stamp Overlap Counter
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests whether a candidate can use a 2D difference array to efficiently count how many rectangular regions overlap each cell of a grid.
Problem Statement
You have an n × n grid where every cell starts at zero. You are given a list of stamps, where each stamp is an axis-aligned rectangle described by [r1, c1, r2, c2]. Applying a stamp increments every cell inside it by 1. Cells at the corners (r1, c1) and (r2, c2) are both included, as is everything in between.
Return the final grid after all stamps have been applied. Each cell (r, c) in the output should hold the total number of stamps that cover it — a stamp covers (r, c) when r1 <= r <= r2 and c1 <= c <= c2.
Your implementation must not modify the input list, and it must handle up to 10⁵ stamps on a 1000 × 1000 grid without iterating over every covered cell for each stamp.
Constraints
1 <= n <= 10000 <= len(stamps) <= 10^5- Each element of
stampshas exactly 4 integers. 0 <= r1 <= r2 < n0 <= c1 <= c2 < n- Duplicate entries in
stampsare allowed and each one contributes independently to the count.
Examples
Example 1
Input: stamp_overlap_grid(3, [[0, 0, 1, 1], [1, 1, 2, 2]])
Output: [[1, 1, 0], [1, 2, 1], [0, 1, 1]]
Example 2
Input: stamp_overlap_grid(2, [])
Output: [[0, 0], [0, 0]]
Hints
Hint 1
Start with the 1D version: how would you add 1 to every index in a range [a, b] across many ranges without visiting each index one by one? Think about what a single +1 and -1 can do when you take a prefix sum afterward.
Hint 2
Extend that idea to two dimensions. A single value placed at (r1, c1) in a difference grid will spread to the entire quadrant below and to the right once you compute a 2D prefix sum — figure out how to place values at the other three corners to cancel out everything outside the rectangle.
Hint 3
Make sure your difference grid is (n+1) × (n+1), not n × n. When a rectangle touches the last row or column, the cancelling marks land at index n, which would be out of bounds on a smaller grid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why not the naive approach?
Visiting every cell of every stamp costs O(k · n²) in the worst case. With k = 10⁵ stamps each covering a 1000 × 1000 grid that is 10¹¹ operations — far too slow.
1D warm-up: difference arrays
To add 1 to every index in a range [a, b] of a 1D array, write +1 at position a and -1 at position b + 1. A single prefix-sum pass over the difference array then reconstructs the full result. The key insight: one write records the start, one write cancels it past the end, and the prefix sum does all the spreading in O(n).
Extending to 2D
In a 2D difference grid, a value placed at (r, c) contributes to every cell (r', c') with r' >= r and c' >= c once you take the 2D prefix sum. That means a lone +1 at (r1, c1) would bleed into an infinite bottom-right quadrant. To confine it to the rectangle [r1, c1] → [r2, c2], apply inclusion-exclusion at four corners:
| Position | Value | Effect after prefix sum |
|---|---|---|
(r1, c1) | +1 | covers the full quadrant below-right |
(r1, c2+1) | −1 | subtracts the quadrant right of c2 |
(r2+1, c1) | −1 | subtracts the quadrant below r2 |
(r2+1, c2+1) | +1 | the bottom-right quadrant was subtracted twice, so restore it |
For any cell (r, c) you can verify which marks are included (those at or above-left of (r, c)) and confirm the net contribution is exactly 1 inside the rectangle and 0 everywhere else.
Why (n+1) × (n+1)?
When a stamp touches the last row or column (r2 = n−1 or c2 = n−1), the cancelling marks land at index n. An n × n grid would cause an index error. The extra row and column absorb those marks safely; they are never read when building the output.
Prefix-sum pass
Iterating row by row, a running row_sum accumulates the horizontal prefix for each row's slice of diff. Adding the already-completed value from the row above gives the full 2D prefix sum in one pass, without a separate subtraction step.
Correctness for edge cases
- No stamps:
diffstays all zeros; the output is an all-zero grid. - Single-cell stamp (
r1 == r2,c1 == c2): the four marks surround exactly one cell, so only that cell receives 1. - Full-grid stamp
[0, 0, n−1, n−1]: all three cancelling marks land in rownor columnnand are never read; every output cell gets 1. - Duplicate stamps: each copy writes its own four marks independently, so duplicates add up correctly.
- Non-mutation: the loop only reads from
stamps; all writes go to freshly allocateddiffandresultarrays.
Complexity
- Time: O(k + n²) — O(1) per stamp for the four corner writes, then one O(n²) prefix-sum sweep.
- Space: O(n²) for the
(n+1)²difference grid and then²output. The output itself is Θ(n²), so this is optimal up to a constant.
Reference solution
from typing import List
def stamp_overlap_grid(n: int, stamps: List[List[int]]) -> List[List[int]]:
# Use an (n+1) x (n+1) difference grid so that r2+1 and c2+1 are always
# valid indices even when r2 or c2 equals n-1.
diff = [[0] * (n + 1) for _ in range(n + 1)]
for r1, c1, r2, c2 in stamps:
# Four-corner inclusion-exclusion update:
# +1 at (r1, c1) starts the covered quadrant
# -1 at (r1, c2+1) cancels columns to the right of c2
# -1 at (r2+1, c1) cancels rows below r2
# +1 at (r2+1, c2+1) restores the bottom-right quadrant subtracted twice
diff[r1][c1] += 1
diff[r1][c2 + 1] -= 1
diff[r2 + 1][c1] -= 1
diff[r2 + 1][c2 + 1] += 1
# Recover counts via a single 2D prefix-sum sweep.
# result[r][c] = sum of diff[i][j] for all i <= r, j <= c.
result = [[0] * n for _ in range(n)]
for r in range(n):
row_sum = 0
for c in range(n):
row_sum += diff[r][c]
if r:
result[r][c] = result[r - 1][c] + row_sum
else:
result[r][c] = row_sum
return result