Count Shelf Sub-Rectangles Whose Stock Sums to a Target
Last updated: November 29, 2026
Quick Overview
Given a grid of integer stock deltas (positive or negative), count how many sub-rectangles have a sum exactly equal to a target value.
Amazon
November 29, 20260
0
0 solved
Given a grid of integer stock deltas (positive or negative), count how many sub-rectangles have a sum exactly equal to a target value.
This extends the one-dimensional subarray-sum counting idea to two dimensions, a favorite Amazon onsite escalation. The interviewer wants you to fix a pair of rows, compress columns, and reuse the prefix sum plus hash map counting trick.
What the Interviewer Expects
- Start with the 1D version: count subarrays summing to k using a prefix-count map
- Fix a top row and extend the bottom row, accumulating column sums
- Run the 1D counter on the compressed column array for each row pair
- Achieve O(m^2 * n) time
- Iterate over the smaller dimension as rows
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Why does a sliding window not work here?
- How would you find the max-sum sub-rectangle instead?
- How would you count rectangles with sum at most k?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: an m x n grid of integers (may be negative) and target k. Output: the number of (r1, r2, c1, c2) rectangles whose cell sum equals k. Grids are up to about 100 x 100....
High-Level Design
For each top row top, keep an array cols where cols[j] is the sum of column j from row top to the current bottom row. Each time the bottom row advances, add that row into cols, then count suba...