Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The largest square of ones

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazonGoogleCitadel

Given a grid of 0s and 1s, return the area of the largest square containing only 1s.

Examples

InputOutputWhy
grid = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]4A 2 × 2 square in the middle right.
grid = [[0,1],[1,0]]1Single cells only.
grid = [[0]]0No ones.

Constraints

  • 1 ≤ rows, cols ≤ 300
  • Every cell is 0 or 1

Hints

Hint 1

Let side[r][c] be the side of the largest all-ones square whose bottom-right corner is (r, c).

Hint 2

For a 1: side = 1 + min(side above, side to the left, side diagonally up-left).

Hint 3

The answer is the largest side, squared.

Where people lose marks

  • Returning the side instead of the area.
  • Using only the up and left neighbours, which allows an L-shaped hole at the diagonal.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.