Problem · Array

Report Island Areas in Discovery Order

Learn this problem
MediumSnap Inc. logoSnap Inc.FULLTIMEPHONE SCREEN

Problem statement

Given a rectangular binary matrix grid, return the area of every island.

An island is a maximal group of cells containing 1 connected horizontally or vertically. Its area is its number of cells.

Scan cells in row-major order, from top to bottom and left to right. When an unvisited land cell starts a new island, append that island's area to the result. Return an empty array when the grid contains no land.

Function

islandAreas(grid: int[][]) → int[]

Examples

Example 1

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

The scan first reaches the three-cell island in the upper-left, then the three-cell island in the lower-right.

Example 2

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

The two one-cell islands are discovered before the three-cell island in the bottom row.

Example 3

grid = [[0, 0], [0, 0]]return = []

The grid contains no land, so there are no island areas to report.

Constraints

  • 1 <= grid.length <= 300
  • 1 <= grid[i].length <= 300
  • Every row has the same length.
  • grid[i][j] is either 0 or 1.

More Snap Inc. problems

drafts saved locally
public int[] islandAreas(int[][] grid) {
    // Write your code here.
}
grid[[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 1, 1]]
expected[3, 3]
checking account