KatInterview

Rectangular Stamp Overlap Counter

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashing2d-arrayprefix-sumdifference-array

Last 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 <= 1000
  • 0 <= len(stamps) <= 10^5
  • Each element of stamps has exactly 4 integers.
  • 0 <= r1 <= r2 < n
  • 0 <= c1 <= c2 < n
  • Duplicate entries in stamps are 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.