Smallest Rectangle Enclosing Black Pixels - Problem
Imagine you're working with a digital photograph represented as a binary matrix where 0 represents white pixels and 1 represents black pixels. You know that all black pixels form a single connected region (like a blob of ink on paper).
Your task is to find the smallest axis-aligned rectangle that completely encloses all the black pixels. Think of it like drawing the tightest possible rectangular frame around a shape.
Key constraints:
- The matrix is
m x nin size - All black pixels (1s) are connected horizontally or vertically
- You're given the coordinates
(x, y)of one black pixel as a starting point - Your algorithm must run in less than O(mn) time complexity
Return the area of the smallest rectangle that encloses all black pixels.
Input & Output
example_1.py โ Basic Rectangle
$
Input:
image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 2
โบ
Output:
6
๐ก Note:
The black pixels form a shape from row 0-2 and columns 1-2, creating a 3ร2 rectangle with area 6
example_2.py โ Single Column
$
Input:
image = [["1"],["1"],["1"]], x = 1, y = 0
โบ
Output:
3
๐ก Note:
All black pixels are in a single column, forming a 3ร1 rectangle with area 3
example_3.py โ L-shaped Region
$
Input:
image = [["1","1","0"],["1","0","0"],["1","0","0"]], x = 0, y = 0
โบ
Output:
6
๐ก Note:
The L-shaped black region requires a 3ร2 bounding rectangle with area 6
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Subject
We know there's black ink at position (x,y) - this is our reference point
2
Smart Boundary Detection
Instead of checking every pixel, use binary search to quickly find edges
3
Search Left Edge
Binary search columns from 0 to y to find leftmost black pixels
4
Search Right Edge
Binary search columns from y to n-1 to find rightmost black pixels
5
Search Vertical Edges
Similarly find top and bottom boundaries using row searches
6
Calculate Frame Size
Multiply width ร height to get the minimum rectangle area
Key Takeaway
๐ฏ Key Insight: By leveraging binary search and the connected region property, we can find rectangle boundaries in logarithmic time instead of linear time, achieving the required sub-O(mn) complexity while maintaining correctness.
Time & Space Complexity
Time Complexity
O(m log n + n log m)
Four binary searches: 2 on columns (m comparisons each) and 2 on rows (n comparisons each)
โก Linearithmic
Space Complexity
O(1)
Only using a few variables for binary search bounds
โ Linear Space
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'
- The black pixels in the image only form one component
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code