oneby7

Graphs Union-find

468. Most Stones Removed with Same Row or Column

Medium

Stones lie on a large board, each at a point with whole-number coordinates. A stone at [x, y] sits in row x and column y. No two stones are at the same point.

You may remove a stone if at least one other stone still on the board is in the same row or the same column. You remove stones one at a time, in any order you like.

You are given the positions in stones. Return the largest number of stones you can remove.

Example 1

Input: stones = [[0, 0], [0, 3], [2, 3], [2, 5], [4, 1]]

Output: 3

Explanation: Remove [2,5], which shares row 2 with [2,3]. Then remove [2,3], which shares column 3 with [0,3]. Then remove [0,3], which shares row 0 with [0,0]. Now [0,0] and [4,1] share no row or column with any stone, so they stay.

Example 2

Input: stones = [[1, 2], [2, 3], [3, 1]]

Output: 0

Explanation: The three stones are in three different rows and three different columns. The row number of one stone is the column number of another, but a row and a column are different lines, so no stone can go.

Example 3

Input: stones = [[0, 7], [4, 7], [1000000000, 7]]

Output: 2

Explanation: All three stones are in column 7, so any two of them can go, one after the other.

Check your understanding

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

stones = [[2, 0], [2, 6], [5, 6], [1, 1], [1, 3], [4, 5], [9, 3]]

Constraints

  • 1 ≤ stones.length ≤ 105
  • stones[i].length == 2
  • 0 ≤ xi, yi ≤ 109
  • No two stones are at the same point.

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.