Count All-Healthy Rectangles in a Rack Health Matrix

Last updated: November 29, 2026

Quick Overview

Given a binary matrix where 1 means a server slot is healthy, count how many axis-aligned sub-rectangles consist entirely of 1s.

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

0

0

0 solved


Given a binary matrix where 1 means a server slot is healthy, count how many axis-aligned sub-rectangles consist entirely of 1s.

A harder Meta onsite question that builds on the histogram idea from largest-rectangle problems but asks for a count instead of a maximum, framed around data center rack health maps. Interviewers check whether you can turn each row into a histogram and count rectangles by their bottom-right corner with a monotonic stack.

What the Interviewer Expects
  • Convert each row to histogram heights of consecutive 1s
  • Count rectangles whose bottom-right corner is at each cell
  • Use a monotonic increasing stack to reuse counts from the previous smaller bar
  • Explain the recurrence cnt[j] = cnt[p] + h[j] * (j - p)
  • Reach O(rows * cols) time
Key Topics to Cover
Monotonic stack
Histogram
Counting
2D 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
  • Return the largest all-ones square instead.
  • Count rectangles with at most one unhealthy slot.
  • How would you update the count when a single cell flips?
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 0/1. Output: the number of sub-rectangles (choose top, bottom, left, right) where every cell is 1. Sizes up to 150 x 150 or bigger, so O((mn)^2) enumeration is too slow, and O(...

High-Level Design

Process row by row. h[j] is the number of consecutive 1s ending at the current row in column j. For a fixed bottom row, count rectangles whose bottom-right cell is (row, j). Let p be the nearest col...


Submit Your Answer
Markdown supported