Answer Rectangular Shelf Inventory Sums With a 2D Prefix Table

Last updated: November 29, 2026

Quick Overview

Given a fixed grid of item counts per shelf slot, answer many queries asking for the total count inside a rectangle (r1, c1) to (r2, c2) in O(1) per query after preprocessing.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Easy

0

0

0 solved


Given a fixed grid of item counts per shelf slot, answer many queries asking for the total count inside a rectangle (r1, c1) to (r2, c2) in O(1) per query after preprocessing.

Inventory dashboards repeatedly sum stock over aisle and level ranges. The interviewer checks that you build a 2D prefix sum with a padding row and column and apply inclusion-exclusion without off-by-one errors.

What the Interviewer Expects
  • Build a (m + 1) x (n + 1) prefix table with a zero border
  • Fill it with inclusion-exclusion in one pass
  • Answer each query with four lookups
  • State O(mn) preprocessing and O(1) per query
  • Mention a Fenwick tree if cells can change
Key Topics to Cover
prefix sums
matrix
inclusion-exclusion
range queries
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if slot counts update between queries?
  • How would you find the rectangle of a fixed size with the largest total?
  • How does memory scale for a 100,000 x 100,000 grid, and what would you do?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: an m x n grid of integers, then a list of queries with inclusive corners. Output: the sum for each query. The grid is static. Queries can number in the millions, so per-query loops over cells a...

High-Level Design

Define P[i][j] as the sum of all cells in rows 0..i-1 and columns 0..j-1. Then P[i+1][j+1] = grid[i][j] + P[i][j+1] + P[i+1][j] - P[i][j]. A query sum equals `P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1]...


Submit Your Answer
Markdown supported