On a 2-D plane, we place 'n' stones at some integer coordinate points. Each coordinate point may have at most one stone.
You are given an array 'stones' of length 'n' where 'stones[i]' = '[ri, ci]' represent the ith stone’s location i.e 'ri' is the row coordinate of the 'ith' stone and 'ci' is the column coordinate of the 'ith' stone. Your task is to return the largest possible number of stones that can be removed.
Input: 'stones' = [[0,1] [1,0] [0,0]]
Output: 2
Explanation:
We can remove the 1st stone at [0,1] as it has the same row as the 3rd stone [0, 0]. And remove the 2nd stone because it has the same column [0,1] as the 3rd stone.
The first line of input contains a single integer 'n', which represents the number of stones.
The following 'n' lines of the input contain the coordinates of the stones, where each line contains two space-separated integers representing the row and column, respectively.
Return a single line containing a single integer denoting the maximum number of stones that can be removed.
You don't have to print anything. It's been already taken care of. Just implement the given function.
5
2 0
2 1
3 1
3 2
5 5
3
3
For this test case:
The answer will be 3:
We can remove the stone at [2,1] because it has the same row as the stone [2,0], stone at [3,1] because it has the same column as [2,1] and stone at [3,2] because it shares the same row as [3,1].
1
1 1
0
0
Try to do this in O(n*log(n)).
1 <= n <= 10^4
0 <= stones[i][j] <= 10^3
Time limit: 1 second
Can we find connected components via DSU?
The main idea is to use a DSU data structure, to find connected components. A DSU data structure can be used to maintain knowledge of the connected components of a graph, and query for them quickly. In particular, we would like to support two operations:
Following are the steps :
O(N * log(N)), where ‘N’ is the size of the array.
We make ‘N’ queries for union which take at worst log(N) time, hence O(N * log(N).
O(N), where ‘N’ is the size of the array.
Since we are keeping track of the parent nodes, which is equal to the size of the array, hence space complexity: O(N).