FastPrepLargest All-One Square Area and Count

Largest All-One Square Area and Count

NVIDIA logoNVIDIA● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Given a rectangular binary matrix matrix, find the largest nonempty square containing only 1 cells and count how many squares have that maximum area.

A square uses consecutive rows and consecutive columns with the same positive side length. Count each distinct top-left coordinate and side length once. Overlapping squares count separately.

Return [maximumArea, numberOfMaxima] in that order. Only squares with the largest area contribute to the count. If the matrix has no rows, no columns, or no 1 cells, return [0, 0].

Function

largestSquareAreaAndCount(matrix: int[][]) → int[]

Examples

Example 1

matrix = [[1,1,1],[1,1,1]]return = [4,2]

The two squares with side length 2 start at (0, 0) and (0, 1). They overlap and each has area 4. The six smaller squares do not contribute to the count.

Example 2

matrix = [[1,0,1],[0,1,0]]return = [1,3]

Each of the three 1 cells is a square with area 1. No larger square is entirely ones.

Example 3

matrix = [[0,0],[0,0]]return = [0,0]

No nonempty all-one square exists, so both the maximum area and its count are 0.

Constraints

  • 0 <= matrix.length <= 100.
  • Every row has the same length, between 0 and 100 inclusive.
  • Every cell is 0 or 1.

More NVIDIA problems

See NVIDIA hiring insights
public int[] largestSquareAreaAndCount(int[][] matrix) {
    // Return the maximum square area and the number of squares having it.
}
matrix[[1,1,1],[1,1,1]]
expected[4,2]
Checking account…