Katkat

Find the Maximum Island Area

AmazonSoftware Engineer · Online Assessment

Last updated

Find the largest four-neighbor island area in a binary matrix, including the component-size challenges of row-by-row streaming.

Given a two-dimensional binary matrix, return the maximum area of any island. An island is a connected component of cells containing 1, using only up, down, left, and right adjacency. Its area is the number of cells in that component. Diagonal contact does not connect islands.

Input and Output

  • Input: a rectangular matrix containing only 0 and 1.
  • Output: one integer, the largest island area.
  • For this practice version, an empty matrix or a matrix with no land has answer 0.

Example

grid = [
 [1, 1, 0],
 [0, 1, 0],
 [1, 0, 1]
]
answer = 3

The upper-left island has three cells, which is larger than either one-cell island in the last row.

Discussion Extension

How would you maintain the maximum island area if matrix rows arrived one at a time? The source asks about row streaming but supplies no streaming-call interface; the function above receives the complete matrix.