Largest Square of Ones

Quick Overview

Compute the area of the largest all-ones square in a binary matrix in linear time while using only one row of dynamic-programming state.

Largest Square of Ones

Company: Airwallex

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

# Largest Square of Ones Implement `largest_square_area(matrix: list[list[int]]) -> int`. Given a rectangular binary matrix, return the area of the largest axis-aligned square whose cells are all `1`. ### Input Domain - `0 <= len(matrix) <= 2,000`. - If the matrix is nonempty, every row has the same length between `0` and `2,000`. - The matrix contains at most `1,000,000` cells. - Every cell is exactly `0` or `1`. ### Output Rules - Return the square's area, not its side length. - Return `0` for an empty matrix, a matrix with empty rows, or a matrix containing no `1`. - If several largest squares exist, return their shared area. ### Constraints - Target time is `O(rows * columns)`. - Additional space may be reduced to `O(columns)`. ### Examples #### Example 1 Input: `matrix = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]` Output: `4` #### Example 2 Input: `matrix = [[0,0],[0,0]]` Output: `0` ```hint Describe squares by their lower-right corner For a cell containing one, consider what the neighboring partial answers imply about a square ending at that cell. ```

Quick Answer: Compute the area of the largest all-ones square in a binary matrix in linear time while using only one row of dynamic-programming state.

|Home/Coding & Algorithms/Airwallex
Airwallex logo
Airwallex
Sep 2, 2026
mediumSoftware EngineerTechnical ScreenCoding & Algorithms
1
0

Largest Square of Ones

Implement largest_square_area(matrix: list[list[int]]) -> int.

Given a rectangular binary matrix, return the area of the largest axis-aligned square whose cells are all 1.

Input Domain

  • 0 <= len(matrix) <= 2,000 .
  • If the matrix is nonempty, every row has the same length between 0 and 2,000 .
  • The matrix contains at most 1,000,000 cells.
  • Every cell is exactly 0 or 1 .

Output Rules

  • Return the square's area, not its side length.
  • Return 0 for an empty matrix, a matrix with empty rows, or a matrix containing no 1 .
  • If several largest squares exist, return their shared area.

Constraints

  • Target time is O(rows * columns) .
  • Additional space may be reduced to O(columns) .

Examples

Example 1

Input: matrix = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]

Output: 4

Example 2

Input: matrix = [[0,0],[0,0]]

Output: 0

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...