FastPrepLargest Component in Three Rows

Largest Component in Three Rows

Google logoGoogle● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

You are given a binary matrix matrix with exactly three rows and n columns. A component is a maximal group of cells containing 1 connected through horizontal or vertical neighbors.

Return the number of cells in the largest component, or 0 when there are no ones. Diagonal contact does not connect cells.

Your final solution must run in O(n) time using O(1) auxiliary space. The supplied matrix is excluded from the auxiliary-space count.

Function

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

Examples

Example 1

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

The final column joins the upper and lower runs into one component of seven cells.

Example 2

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

The middle column separates the frontier into two tails of the same earlier component. Rejoining them must count the old cells only once.

Example 3

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

Components contain only ones, so an all-zero matrix returns 0.

Constraints

  • matrix.length == 3.
  • 1 <= n <= 100000, and every row has length n.
  • Every cell is 0 or 1.

More Google problems

See Google hiring insights
public int largestThreeRowComponent(int[][] matrix) {
    // Write your code here
}
matrix[[1,1,1],[0,0,1],[1,1,1]]
expected7
Checking account…