Answer Rectangle Sum Queries Over a Population Density Grid

Last updated: November 29, 2026

Quick Overview

Given a fixed m x n grid of population counts for map cells, preprocess it so that each query (r1, c1, r2, c2) returns the total population of the inclusive rectangle in O(1) time.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a fixed m x n grid of population counts for map cells, preprocess it so that each query (r1, c1, r2, c2) returns the total population of the inclusive rectangle in O(1) time.

A Google screen question framed around Maps analytics, where many rectangle queries hit a static density layer. The interviewer checks that you build a 2D prefix sum with a padded border and get the inclusion-exclusion signs right.

What the Interviewer Expects
  • Builds a (m+1) x (n+1) prefix table to avoid boundary branches
  • States the inclusion-exclusion formula for both build and query
  • Answers each query in O(1)
  • Discusses the trade-off when the grid also receives updates
  • Validates or clamps query coordinates
Key Topics to Cover
2D Prefix Sums
Inclusion-Exclusion
Preprocessing
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
  • Cells receive point updates between queries; what structure would you use?
  • The grid is 100k x 100k and sparse; how do you store it?
  • Find the k x k window with the largest population.
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
  • Build once from grid (m x n ints, may be negative after corrections).
  • query(r1, c1, r2, c2) with r1 <= r2 and c1 <= c2, inclusive, returns the sum.
  • Many queries, so per-query time must b...
High-Level Design

Let P[i][j] be the sum of the top-left i x j block, using one row and column of zero padding. Then P[i+1][j+1] = grid[i][j] + P[i][j+1] + P[i+1][j] - P[i][j]. A rectangle sum is the big block mi...


Submit Your Answer
Markdown supported