Count Rectangles Whose Four Corners Are All Active Pixels

Last updated: November 29, 2026

Quick Overview

Given an m x n binary image, count the axis-aligned rectangles whose four corner cells are all 1, where corners must be on distinct rows and distinct columns.

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

0

0

0 solved


Given an m x n binary image, count the axis-aligned rectangles whose four corner cells are all 1, where corners must be on distinct rows and distinct columns.

A Google screen counting problem that rewards switching the iteration from corners to row pairs. The interviewer checks for the column-pair counting trick and a sensible complexity discussion when rows are dense or sparse.

What the Interviewer Expects
  • Notices that a rectangle is defined by two rows sharing two 1-columns
  • Counts, for each column pair, how many earlier rows had 1s in both
  • Adds that count when a new row has the pair too
  • Discusses O(m n^2) vs iterating over row pairs
  • Handles single-row and single-column images
Key Topics to Cover
Combinatorics
Hash Maps
Pair Counting
Matrix Traversal
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
  • Rows are very sparse; how would you speed it up?
  • Count only squares instead of all rectangles.
  • Return the rectangle with the largest area.
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: grid of 0/1.
  • A rectangle is chosen by rows r1 < r2 and columns c1 < c2 with all four corners equal to 1.
  • Output: the total count....
High-Level Design

Process rows top to bottom. For a row, list its 1-columns and enumerate every pair (c1, c2). If pair_count[(c1, c2)] earlier rows also had 1s in both columns, each of those rows closes one rectang...


Submit Your Answer
Markdown supported