Count Every All-Free Rectangle in a Parking Lot Occupancy Grid
Last updated: November 29, 2026
Quick Overview
Given an m x n binary grid where 1 marks a free parking space, count all axis-aligned rectangles (of any size) made entirely of free spaces.
0
0
0 solved
Given an m x n binary grid where 1 marks a free parking space, count all axis-aligned rectangles (of any size) made entirely of free spaces.
A Google onsite Hard counting problem that builds on histogram techniques. The interviewer expects an O(mn * n) solution at minimum and is impressed by the monotonic-stack O(mn) version with a clear explanation of what each stack entry contributes.
What the Interviewer Expects
- Builds per-column heights of consecutive free cells ending at the current row
- Counts rectangles whose bottom-right corner is each cell
- Gives the O(m n^2) scan-left-with-min approach
- Optimizes to O(mn) with a monotonic stack
- Explains the stack recurrence clearly
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
- Count only squares.
- Return the number of rectangles of each area.
- Spaces get freed and occupied over time; how would you update counts?
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:
gridof 0/1. - Output: the number of all-1 rectangles of any size.
- A 2 x 2 all-ones grid has 9 (four 1x1, two 1x2, two 2x1, one 2x2)....
High-Level Design
Fix the bottom row. h[c] is the number of consecutive 1s ending at this row in column c. Count rectangles whose bottom-right corner is (row, c): extending left to column j, the height is limited b...