Skip to main content
LeetCode 302, Hard. Topics: Depth-First Search, Breadth-First Search, Array, Binary Search, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

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

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.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026