Smallest Rectangle Enclosing Black Pixels

Binary search the four bounding rows/columns by checking if each side contains any black pixel.

Hard
Time O(m log n + n log m) Space O(1)
LeetCode
7 min read
binary-search matrix

Problem#

Given a black-and-white image ('1' is black, '0' is white) and the coordinates (x, y) of one black pixel, return the area of the smallest axis-aligned rectangle that contains all black pixels. All black pixels are connected.

Examples#

  • image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 26
  • image = [["1"]], x = 0, y = 01

Constraints#

  • 1 <= m, n <= 100, at least one black pixel exists.

Approach#

For each of the four boundaries, define a monotone predicate “this row/column contains a black pixel” and binary search the extreme row/column. Connectivity guarantees the predicate flips exactly once on each side of (x, y).

Solution#

Smallest Rectangle Enclosing Black Pixels
class Solution {
public:
int minArea(vector<vector<char>>& image, int x, int y) {
int m = image.size(), n = image[0].size();
auto rowHasBlack = [&](int r) {
for (int j = 0; j < n; ++j) if (image[r][j] == '1') return true;
return false;
};
auto colHasBlack = [&](int c) {
for (int i = 0; i < m; ++i) if (image[i][c] == '1') return true;
return false;
};
int top = bsearch(0, x, true, rowHasBlack);
int bottom = bsearch(x + 1, m, false, rowHasBlack);
int left = bsearch(0, y, true, colHasBlack);
int right = bsearch(y + 1, n, false, colHasBlack);
return (bottom - top) * (right - left);
}
private:
template<class F>
int bsearch(int lo, int hi, bool findFirstTrue, F pred) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (findFirstTrue) {
if (pred(mid)) hi = mid;
else lo = mid + 1;
} else {
if (pred(mid)) lo = mid + 1;
else hi = mid;
}
}
return lo;
}
};

Editorial#

Each binary search runs O(log dimension) iterations and each iteration scans an entire row or column in linear time. The connectivity of black pixels makes the predicate monotone on either side of the given point — that’s what unlocks binary search over a 2D image.

Complexity#

  • Time: O(m log n + n log m).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.