Answer Rectangle Sum Queries Over an Engagement Heatmap

Last updated: November 29, 2026

Quick Overview

Given a fixed 2D grid of engagement counts, support many queries that return the sum inside a rectangle defined by its top-left and bottom-right corners.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given a fixed 2D grid of engagement counts, support many queries that return the sum inside a rectangle defined by its top-left and bottom-right corners.

A Meta phone screen question about precomputation, framed as an Ads Manager heatmap where advertisers repeatedly sum impressions over regions and hours. The interviewer is checking the 2D prefix sum construction and the inclusion-exclusion formula, plus the trade-off once updates are allowed.

What the Interviewer Expects
  • Build a 2D prefix sum with a padding row and column
  • Apply inclusion-exclusion for each query in O(1)
  • Explain why the padding removes boundary special cases
  • Discuss the update follow-up with a 2D Fenwick tree
  • Validate the formula on a small example
Key Topics to Cover
Prefix sums
Inclusion-exclusion
Precomputation
Fenwick tree
Matrix
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
  • How would you support point updates efficiently?
  • What if the grid is too large for memory but queries are known ahead of time?
  • How would you find the rectangle with the largest sum?
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
  • Grid up to 200 x 200, up to 10^4 queries.
  • Query corners are inclusive and valid.
  • The grid does not change between queries....
High-Level Design

Let P[r][c] be the sum of all cells above and left of (r, c), exclusive, using an extra zero row and column. Then the sum of the rectangle (r1, c1) to (r2, c2) is `P[r2+1][c2+1] - P[r1][c2+1] ...


Submit Your Answer
Markdown supported