FastPrepForeground Region Sizes
Problems/Foreground Region Sizes

Foreground Region Sizes

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report provides a rectangular binary matrix, four-neighbor foreground connectivity, and first-encounter row-major output order. No additional domain behavior is introduced.

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

  • Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
  • Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
  • Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
All Microsoft interview questionsSee Microsoft hiring insights
Saved
class Solution {
    public int[] getRegionSizes(int[][] grid) {
        // Write your solution here.
    }
}
Checking account…