Smallest Rectangle Enclosing Black Pixels - Problem

You are given an m x n binary matrix image where 0 represents a white pixel and 1 represents a black pixel.

The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.

Given two integers x and y that represent the location of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.

You must write an algorithm with less than O(mn) runtime complexity.

Input & Output

Example 1 — Basic Connected Region
$ Input: image = [[0,0,1,0],[0,1,1,0],[0,1,0,0]], x = 0, y = 2
Output: 6
💡 Note: Black pixels form connected region from (0,2) to (2,1). Rectangle bounds: rows [0,2], columns [1,2]. Area = (2-0+1) × (2-1+1) = 3 × 2 = 6
Example 2 — Single Black Pixel
$ Input: image = [[1]], x = 0, y = 0
Output: 1
💡 Note: Only one black pixel at (0,0). Rectangle is 1×1, so area = 1
Example 3 — Horizontal Line
$ Input: image = [[1,1,1]], x = 0, y = 1
Output: 3
💡 Note: Black pixels form horizontal line. Rectangle bounds: row [0,0], columns [0,2]. Area = 1 × 3 = 3

Constraints

  • m == image.length
  • n == image[i].length
  • 1 ≤ m, n ≤ 100
  • image[i][j] is either 0 or 1
  • 0 ≤ x < m
  • 0 ≤ y < n
  • image[x][y] == 1

Visualization

Tap to expand
Smallest Rectangle Enclosing Black Pixels INPUT Binary Matrix (m x n) 0 0 1 0 0 1 1 0 0 1 0 0 Starting pixel (x=0, y=2) image = [[0,0,1,0], [0,1,1,0], [0,1,0,0]] x = 0, y = 2 0 1 2 0 1 2 3 ALGORITHM STEPS 1 Binary Search Left Find leftmost col with 1 left = 1 2 Binary Search Right Find rightmost col with 1 right = 2 3 Binary Search Top Find topmost row with 1 top = 0 4 Binary Search Bottom Find bottommost row with 1 bottom = 2 Time Complexity O(m log n + n log m) Better than O(mn)! Area Formula: (right-left+1) * (bottom-top+1) FINAL RESULT Enclosing Rectangle 0 0 1 0 0 1 1 0 0 1 0 0 width = 2 height = 3 Calculation: (2-1+1) * (2-0+1) = 2 * 3 = 6 OUTPUT Area = 6 Key Insight: Use Binary Search on rows and columns instead of scanning entire matrix. For each column, binary search checks if ANY cell in that column has a 1 (O(m) check). Since black pixels are connected, we can find boundaries via 4 binary searches: left, right, top, bottom. TutorialsPoint - Smallest Rectangle Enclosing Black Pixels | Optimal Binary Search Approach
Asked in
Google 42 Facebook 28 Microsoft 23 Amazon 19
28.5K Views
Medium Frequency
~25 min Avg. Time
987 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen