oneby7

Graphs Union-find

465. Number of Islands II

Hard

You are given the size of a map, m rows and n columns. At first every cell is water. Then land is added one cell at a time: positions[i] = [r, c] turns the cell in row r and column c into land.

An island is a group of land cells joined by steps up, down, left or right. Two land cells that touch only at a corner are not joined. Everything outside the map is water.

Return a list with one number per position: the number of islands right after that cell is added. A position can appear more than once. Adding land to a cell that is already land changes nothing.

Example 1

Input: m = 3 n = 4 positions = [[0, 0], [0, 1], [1, 2], [2, 1], [0, 3], [1, 1]]

Output: [1,1,2,3,4,2]

Explanation: Cell (0,1) joins the island at (0,0). Cells (1,2), (2,1) and (0,3) each start a new island, which makes four. The last cell, (1,1), touches the islands at (0,1), (1,2) and (2,1), so those three and the new cell become one island. With (0,3), that leaves two.

Example 2

Input: m = 2 n = 2 positions = [[0, 0], [1, 1], [0, 1], [1, 0], [0, 0]]

Output: [1,2,1,1,1]

Explanation: Cell (0,1) joins the two corner islands into one. Cell (1,0) touches two land cells too, but they are already one island, so the count stays 1. The last position is already land, so nothing changes.

Example 3

Input: m = 1 n = 5 positions = [[0, 4], [0, 0], [0, 2], [0, 1], [0, 3]]

Output: [1,2,3,2,1]

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ m, n ≤ 104
  • m × n ≤ 106
  • 1 ≤ positions.length ≤ 105
  • positions[i].length == 2
  • 0 ≤ ri < m, 0 ≤ ci < n

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.