Problem Description
Given an m x n binary matrix where '0' represents a white pixel and '1' a black pixel, and knowing that all black pixels form a single connected component, determine the area of the smallest axis-aligned rectangle that encloses all black pixels. A black pixel's coordinate (x, y) is provided as an input, and the solution must run in less than O(m*n) time.
Key Insights
- The black pixels are connected in one region, ensuring a continuous block.
- Instead of scanning every pixel, binary search can be applied on rows and columns to find boundaries.
- The challenge is to efficiently determine the topmost, bottommost, leftmost, and rightmost rows/columns that contain a black pixel.
Space and Time Complexity
Time Complexity: O(mlogn + nlogm)
Space Complexity: O(1)
Solution
The approach uses four binary searches to find the extreme boundaries:
- Search for the left boundary: the smallest column index with a black pixel.
- Search for the right boundary: the largest column index with a black pixel.
- Search for the top boundary: the smallest row index with a black pixel.
- Search for the bottom boundary: the largest row index with a black pixel.
For each binary search, we check if a row/column contains any black pixel and update search bounds accordingly. The area is then calculated as: Area = (right boundary - left boundary + 1) * (bottom boundary - top boundary + 1)
This method leverages the sorted nature of row and column indices (via binary search), resulting in a performance better than scanning every cell.