# MINRECT - Editorial

**URL:** <https://discuss.codechef.com/t/minrect-editorial/126135>\
**Category:** editorial\
**Tags:** cakewalk, editorial, start263\
**Created:** [November 4, 2026, 4:30pm UTC](https://discuss.codechef.com/t/minrect-editorial/126135 "2026-11-04T16:30:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![iceknight1093](https://www.codechef.com/sites/all/themes/abessive/images/user_default_thumb.jpg) [@iceknight1093](https://discuss.codechef.com/u/iceknight1093)\
**Post date:** [November 4, 2026, 4:30pm UTC](https://discuss.codechef.com/t/minrect-editorial/126135/1 "2026-11-04T16:30:17Z")

</div>

# PROBLEM LINK:

[Practice](https://www.codechef.com/problems/MINRECT)  
[Contest: Division 1](https://www.codechef.com/START263A/problems/MINRECT)  
[Contest: Division 2](https://www.codechef.com/START263B/problems/MINRECT)  
[Contest: Division 3](https://www.codechef.com/START263C/problems/MINRECT)  
[Contest: Division 4](https://www.codechef.com/START263D/problems/MINRECT)

_ **Author:** _ [iceknight1093](https://www.codechef.com/users/iceknight1093)  
_ **Tester:** _ [raysh07](https://www.codechef.com/users/raysh07)  
_ **Editorialist:** _ [iceknight1093](https://www.codechef.com/users/iceknight1093)

# DIFFICULTY:

Cakewalk

# PREREQUISITES:

None

# PROBLEM:

Given an N\times M binary grid, find the smallest area of a rectangle that contains all the ones in the grid.

# EXPLANATION:

The constraints are small, so brute force works.  
However, there is a smarter solution.

Let l denote the leftmost column that contains a 1, and r denote the rightmost column that contains a 1.  
Similarly, let u and d denote the uppermost and lowermost rows that contain a 1.

Then, observe that for the rectangle we choose:

- All columns from l to r must be included; if not we’ll miss some 1.
- All rows from u to d must be included; if not we’ll miss some 1.
- Columns \lt l or \gt r are not important, similarly rows \lt u or \gt d are not important.

Thus, it’s optimal to just take all columns from l to r and rows from u to d.  
The area of this rectangle is just (r-l+1) \cdot (d-u+1).

# TIME COMPLEXITY:

\mathcal{O}(NM) per testcase.

# CODE:

> **Editorialist's code (PyPy3)**
>
> ```python
> for _ in range(int(input())):
> n, m = map(int, input().split())
> grid = [input() for i in range(n)]
> l, r, u, d = m, 0, n, 0
>     
> for i in range(n):
> for j in range(m):
> if grid[i][j] == '1':
> l = min(l, j)
> r = max(r, j)
> u = min(u, i)
> d = max(d, i)
> print((r-l+1) * (d-u+1))
> 
> ```
