Search⌘ K
AI Features

Most Stones Removed with Same Row or Column

Explore how to solve the problem of removing the most stones placed on a 2D plane that share rows or columns. Understand and apply the union find algorithm to identify connected components and calculate the maximum stones removable under given constraints.

Statement

Given an array of nn stones in a two-dimensional plane, where each stone is represented by a pair of x and y coordinates, find the maximum number of stones we can remove with the following condition:

A stone can be removed if it shares either the same row or the same column with another stone that has not been removed so far.

Stones are provided as an array, stones, of length nn, where stones[i]=[xi,yi]stones[i] = [x_i, y_i] represents the ithi^{th} stone. Return the maximum possible number of stones that can be removed.

Constraints:

  • 11\leq stones.length 1000\leq 1000
  • 0xi,yi500\leq x_i, y_i \leq50

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Most Stones Removed with Same Row or Column

1.

What is the maximum number of stones we can remove for the following input?

stones = [[0, 1],[1, 0],[1, 1],[2, 0]]

A.

0

B.

3

C.

4

D.

1


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in RemoveStone.java in the following coding playground. The supporting code template provided in UnionFind.java is meant to assist in developing your solution to the problem.

Java
usercode > RemoveStones.java
/*
⬅️ We have provided a UnionFind.java file under the "Files" tab
of this widget. You can use this file to build your solution.
*/
import java.util.*;
class RemoveStones {
public static int removeStones(int[][] stones) {
// Replace this placeholder return statement with your code
return -1;
}
}
Most Stones Removed with Same Row or Column