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
Find Smallest Rectangle Enclosing Black PixelsInput MatrixGiven: (x=0, y=2)Bounding RectangleRectangle: 3 rows × 2 colsArea = 3 × 2 = 6Boundaries: rows [0,2], columns [1,2]
Understanding the Visualization
1
Input Matrix
Binary matrix with connected black pixels and known position
2
Find Boundaries
Determine min/max rows and columns containing black pixels
3
Calculate Area
Rectangle area from boundary coordinates
Key Takeaway
🎯 Key Insight: Use binary search on boundaries instead of scanning entire matrix to achieve sub-O(mn) complexity
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