Count Rectangular Regions of an Ad Revenue Grid Summing to Target

Last updated: November 29, 2026

Quick Overview

Given a grid of daily revenue deltas (which can be negative) and a target, count the non-empty rectangular submatrices whose values sum exactly to the target.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a grid of daily revenue deltas (which can be negative) and a target, count the non-empty rectangular submatrices whose values sum exactly to the target.

A harder Meta onsite question that combines 2D prefix reasoning with the 1D subarray-sum hash map trick. Framed as auditing an ads revenue grid of regions by days for blocks that net to a reconciliation amount. Interviewers expect the O(R^2 C) solution and the transposition trick to choose the smaller dimension.

What the Interviewer Expects
  • Reduce to the 1D problem by fixing a top and bottom row
  • Maintain running column sums as the bottom row grows
  • Count subarrays with a target sum using a prefix hash map
  • Transpose so the squared dimension is the smaller one
  • Handle negative values, which rule out sliding windows
Key Topics to Cover
Prefix sums
Hash map
Subarray sum
Matrix
Dimension reduction
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
  • Why does a sliding window fail here?
  • Find the maximum sum rectangle instead of counting.
  • How would you count rectangles with sum at most the target?
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 100 x 100 with values in [-1000, 1000].
  • Count every rectangle (r1, c1, r2, c2) with sum equal to target....
High-Level Design

Fix the top row top and extend bottom downward. Keep col_sums[c], the sum of column c between top and bottom. Every rectangle spanning exactly those rows corresponds to a contiguous subarr...


Submit Your Answer
Markdown supported