FastPrepLargest Island After One Flip

Largest Island After One Flip

Oracle logoOracle● HardFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a square binary matrix grid, change at most one water cell 0 into a land cell 1. An island is a group of land cells connected through shared sides; diagonals do not connect cells.

Return the largest possible island area, measured in cells, after this optional change. Keep the input unchanged. If every cell is already land, return the area of the full grid.

Function

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

Examples

Example 1

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

Changing the top-middle cell connects the top-left and center cells into an island of area 3. No water cell has all three diagonal land cells as side neighbors.

Example 2

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

Changing the only water cell joins it to the three land cells, making area 4.

Example 3

grid = [[0]]return = 1

Changing the one water cell produces one land cell, so the maximum area is 1.

Constraints

  • For this exercise, assume 1 <= grid.length <= 35.
  • For this exercise, assume grid is square: every row has exactly grid.length entries.
  • Every cell is 0 or 1.

More Oracle problems

See Oracle hiring insights
Saved
public int largestIslandAfterFlip(int[][] grid) {
    // Write your code here.
}
grid[[1,0,0],[0,1,0],[0,0,1]]
expected3
Checking account…