FastPrepNumber of Islands II
Problems/Number of Islands II

Number of Islands II

Amazon logoAmazon● HardONSITE INTERVIEW
QuestionFunctionExamples

Problem statement

Source note: This problem is backed by a real Amazon onsite interview report. The report specified an all-water grid, one land addition at a time, four-directional merging, and an island count after every update. It did not include the exact interface, examples, constraints, or duplicate-update behavior. The core task match is about 95%; the judged positions are distinct.

Start with an m by n grid containing only water. For each distinct position [row, col] in positions, turn that cell into land and append the current number of islands to the result.

An island is a maximal group of land cells connected vertically or horizontally. Diagonal cells are not connected.

Interview follow-up

The rest of the discussion covered the DSU approach, how union-find works, edge cases, and the time and space complexity.

Function

numIslands2(m: int, n: int, positions: int[][]) → int[]

Examples

Example 1

m = 3n = 3positions = [[0,0],[0,1],[1,2],[2,1]]return = [1,1,2,3]

The second cell joins the first island. The final two additions are not four-directionally adjacent to existing land.

Example 2

m = 2n = 2positions = [[0,0],[1,1],[0,1]]return = [1,2,1]

The third addition connects the two existing islands into one.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
public int[] numIslands2(int m, int n, int[][] positions) {
  // write your code here
}
Checking account…