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 represents 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
Examples
Example 1: $$ \begin{array}{c c c c} 0 & 0 & \colorbox{gray}{1} & 0 \\ 0 & \colorbox{gray}{1} & \colorbox{gray}{1} & 0 \\ 0 & \colorbox{gray}{1} & 0 & 0 \\ \end{array} $$
|
|
Example 2:
|
|
Solution
Method 1 - Binary Search
To find the smallest rectangle enclosing all black pixels, one intuitive approach would be to perform a Depth-First Search (DFS) or Breadth-First Search (BFS) starting from the given black pixel. However, to achieve a runtime complexity of less than O(mn)
, we can use a binary search.
Approach
- Binary Search:
- Left Boundary: Use binary search to find the smallest column index with a black pixel.
- Right Boundary: Use binary search to find the largest column index with a black pixel.
- Top Boundary: Use binary search to find the smallest row index with a black pixel.
- Bottom Boundary: Use binary search to find the largest row index with a black pixel.
- Calculate the area of the rectangle formed by these boundaries.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m log n + n log m)
because each binary search runs inO(\log n)
and it is run for each row and column. - 🧺 Space complexity:
O(1)
as we use a constant amount of extra space.