Skip to main content

Smallest Rectangle Enclosing Black Pixels - Solution & Explanation

HardPremiumFree on FleetCodeArrayBinary SearchDepth-First SearchBreadth-First Search5 min readAsked at: Google
Practice this problem

Problem Statement

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

 

Example 1:

Input: image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 2
Output: 6

Example 2:

Input: image = [["1"]], x = 0, y = 0
Output: 1

 

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.

Approach Overview

Problem Overview: You get a binary matrix where '1' represents a black pixel and '0' represents white. One black pixel location (x, y) is given. The task is to compute the area of the smallest axis-aligned rectangle that contains every black pixel in the image.

Approach 1: Full Grid Scan (Brute Force) (Time: O(m*n), Space: O(1))

The simplest strategy is scanning the entire grid. Track four boundaries while iterating: minRow, maxRow, minCol, and maxCol. Every time you encounter a '1', update these limits. After the scan, compute the rectangle area using (maxRow - minRow + 1) * (maxCol - minCol + 1). This approach uses only constant space and works for any matrix, but it ignores the fact that one black pixel location is already known, so it wastes time checking every cell.

Approach 2: BFS/DFS Expansion (Time: O(m*n), Space: O(m*n))

Start traversal from the known black pixel and explore all connected black pixels using breadth-first search or depth-first search. Maintain the same boundary variables while visiting each pixel. Each step checks four directions and continues only if the neighbor is also black and not yet visited. Because every black pixel is visited once, the algorithm runs in O(m*n) in the worst case. This approach leverages connectivity and avoids scanning unrelated white areas, but still degrades to full-grid exploration if most cells are black.

Approach 3: Binary Search on Boundaries (Optimal) (Time: O(m log n + n log m), Space: O(1))

The key observation: all black pixels form a connected region, so the rows and columns containing black pixels are contiguous. Instead of exploring every cell, perform binary search to locate each boundary. Search the top boundary between rows 0 and x, the bottom between x and m-1, the left between 0 and y, and the right between y and n-1. For each midpoint row or column, scan across it to check if at least one black pixel exists. Binary search narrows the first and last rows/columns containing '1'. Once boundaries are found, compute the rectangle area. This approach dramatically reduces search space compared with full traversal.

Recommended for interviews: The binary search boundary approach is usually what interviewers expect. It shows you recognized the monotonic property of rows and columns containing black pixels. Mentioning the brute force or BFS/DFS first demonstrates understanding of the grid traversal baseline, but implementing the binary search version proves stronger algorithmic insight with better asymptotic performance.

Solution

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Full Grid ScanO(m*n)O(1)Simple baseline when matrix size is small or when no starting pixel is provided
BFS/DFS TraversalO(m*n)O(m*n)When exploring connected components or when you want to visit only reachable black pixels
Binary Search BoundariesO(m log n + n log m)O(1)Optimal choice when a starting black pixel is known and rows/columns of black pixels are contiguous

Video Solution

LeetCode 302 | Smallest Rectangle Enclosing Black Pixels | BFS | Functional Programming | Java • Sleepy Cracker • 562 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Smallest Rectangle Enclosing Black Pixels easy or hard?
LeetCode classifies this problem as Hard. The challenge is recognizing that rows and columns containing black pixels form contiguous regions, which allows binary search on boundaries instead of scanning the entire matrix.
Smallest Rectangle Enclosing Black Pixels Python/Java solution
Implementations typically scan rows or columns to verify whether a black pixel exists and then use binary search to narrow the boundary indices. The same algorithm works in Python, Java, C++, and Go because it relies only on matrix traversal and index-based binary search.
What is the best approach for Smallest Rectangle Enclosing Black Pixels?
The most efficient approach uses binary search to locate the top, bottom, left, and right boundaries that contain black pixels. Because rows and columns with black pixels form contiguous ranges, binary search can shrink the search space quickly. This produces a time complexity of O(m log n + n log m) with constant extra space.
Is Smallest Rectangle Enclosing Black Pixels asked at Google/Amazon/Meta?
This problem is commonly associated with Google interview preparation and appears frequently in discussions of advanced matrix search techniques. It tests binary search over a grid and understanding of monotonic boundaries in matrices.
What data structure is used in Smallest Rectangle Enclosing Black Pixels?
The problem mainly uses a 2D array (matrix). Depending on the solution, you may also apply BFS or DFS with a queue or recursion stack, or binary search over row and column indices to find rectangle boundaries.
What is the time complexity of Smallest Rectangle Enclosing Black Pixels?
The optimal binary search solution runs in O(m log n + n log m) time because each boundary search performs log steps and scans a row or column. Brute force and BFS/DFS approaches take O(m*n) time since they may inspect every cell in the matrix.
How to solve Smallest Rectangle Enclosing Black Pixels in O(m log n + n log m)?
Perform binary search to locate the first and last rows and columns that contain at least one black pixel. For each candidate row or column during search, scan across it to check whether a '1' exists. Finding four boundaries this way yields the smallest rectangle containing all black pixels.

Ready to solve this problem?

Practice Smallest Rectangle Enclosing Black Pixels with our built-in code editor and test cases.

Practice on FleetCode