FastPrepForeground Region Sizes

Foreground Region Sizes

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A rectangular binary matrix marks background with 0 and foreground with 1. Foreground cells belong to the same region when connected horizontally or vertically.

Scan the matrix in row-major order. Whenever an unvisited foreground cell is encountered, measure its complete region and append the region size to the result. Return sizes in that first-encounter order; do not sort them.

Function

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

Examples

Example 1

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

The regions are discovered from their first cells at (0,0), (0,3), (2,0), and (2,2).

Example 2

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

There is no foreground.

Example 3

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

All five foreground cells are connected through the second row.

Constraints

  • 0 <= grid.length <= 1000.
  • An empty grid returns an empty array.
  • Non-empty rows have equal length at most 1000 and contain only 0 or 1.

More Microsoft problems

See Microsoft hiring insights
public int[] getRegionSizes(int[][] grid) {
    // Write your solution here.
}
grid[[1,1,0,1],[0,1,0,0],[1,0,1,1]]
expected[3,1,1,2]
Checking account…