Most Stones Removed with Same Row or Column

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.

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

Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.

Examples

Example 1:

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

Output: 5

Explanation: One way to remove 5 stones is: remove (2,2) → (2,1) → (1,2) → (1,0) → (0,1). Only (0,0) remains.

Example 2:

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

Output: 3

Explanation: One way to remove 3 stones is: remove (2,2) → (0,2) → (2,0). Stones (0,0) and (1,1) remain.

Example 3:

Input: stones = [[0,0]]

Output: 0

Explanation: A single stone cannot be removed.

Constraints

  • 1 <= stones.length <= 1000
  • 0 <= xi, yi <= 10^4
  • No two stones are at the same coordinate point
Source: Union Find pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle