Leetcode 947: Most Stones Removed with Same Row or Column

grid47
grid47
Exploring patterns and algorithms
Aug 4, 2024 6 min read

You are given a set of stones placed on a 2D plane at various integer coordinate points. A stone can be removed if it shares the same row or column as another stone that has not been removed yet. Your task is to determine the maximum number of stones that can be removed from the plane by performing valid operations.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of stones, where each stone is represented by a pair of integers [xi, yi] indicating its coordinates on the 2D plane.
Example: Input: stones = [[1, 2], [2, 3], [3, 4], [4, 5]]
Constraints:
• 1 <= stones.length <= 1000
• 0 <= xi, yi <= 10^4
• No two stones have the same coordinates.
Output: Return the maximum number of stones that can be removed by performing the valid operations as described.
Example: Output: 3
Constraints:
• The result will always be a non-negative integer.
Goal: The goal is to determine the maximum number of stones that can be removed from the plane by simulating the process of removal based on the given constraints.
Steps:
• 1. Use a union-find (disjoint-set) data structure to track connected stones in the same row or column.
• 2. For each stone, check if it shares a row or column with any other stone that is still present on the plane.
• 3. Union the stones that are in the same row or column, and count how many stones are connected.
• 4. The maximum number of removable stones is the total number of stones minus the number of connected components (isolated stones).
Goal: The problem constraints ensure that the solution handles a large number of stones and coordinates efficiently.
Steps:
• The number of stones is between 1 and 1000.
• Each stone is placed at a unique coordinate point on the 2D plane.
Assumptions:
• All stones are placed at distinct positions.
• The stones can be removed in any valid sequence where a stone shares a row or column with another stone.
Input: Input: stones = [[0, 0], [0, 1], [1, 0], [1, 2], [2, 1], [2, 2]]
Explanation: In this example, the maximum number of stones that can be removed is 5. The stones can be removed as follows: [2, 2] -> [2, 1] -> [1, 2] -> [1, 0] -> [0, 1]. The stone at [0, 0] cannot be removed because it does not share a row or column with any remaining stones.

Input: Input: stones = [[0, 0], [0, 2], [1, 1], [2, 0], [2, 2]]
Explanation: In this case, the maximum number of stones that can be removed is 3. The stones can be removed as follows: [2, 2] -> [2, 0] -> [0, 2]. The stones at [0, 0] and [1, 1] cannot be removed because they do not share rows or columns with any other stones.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus