githubEdit

23. Maximum Stone Removal

βœ… GFG solution to the Maximum Stone Removal problem: find maximum number of removable stones sharing rows or columns using Union-Find and graph connectivity techniques. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given a 2D array stones[][] of non-negative integers where stones[i] = [xi, yi] represents the location of the ith stone on a 2D plane. Your task is to return the maximum possible number of stones that you can remove.

A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. The goal is to maximize the number of stones removed while following this constraint.

Note: Each coordinate point may have at most one stone.

πŸ“˜ 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:
1. Remove [2, 2] (shares row with [2, 1])
2. Remove [2, 1] (shares column with [0, 1])
3. Remove [1, 2] (shares row with [1, 0])
4. Remove [1, 0] (shares column with [0, 0])
5. Remove [0, 1] (shares row with [0, 0])
Stone [0, 0] remains as it cannot be removed.

Example 2

πŸ”’ Constraints

  • $1 \le \text{stones.size()} \le 1000$

  • $0 \le x_i, y_i \le 10^4$

  • No two stones are at the same position

βœ… My Approach

The optimal approach uses Union-Find (Disjoint Set Union) to group stones into connected components based on shared rows or columns:

Union-Find (DSU) Strategy

  1. Component Identification:

    • Stones sharing the same row or column belong to the same connected component.

    • Within each component, all stones except one can be removed.

  2. Coordinate Mapping:

    • Map each row index to a unique identifier.

    • Map each column index to a different unique identifier (offset by 10001 to avoid collision).

    • Union row and column identifiers for each stone.

  3. Path Compression:

    • Implement find operation with path compression for O(Ξ±(n)) amortized time.

    • Union operation merges components by connecting their root parents.

  4. Count Components:

    • After processing all stones, count distinct connected components.

    • Maximum removable stones = Total stones - Number of components.

  5. Key Insight:

    • Each connected component must keep at least one stone.

    • All other stones in that component can be removed.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n Γ— Ξ±(n)), where n is the number of stones and Ξ±(n) is the inverse Ackermann function, which is nearly constant for all practical values. Each union and find operation takes O(Ξ±(n)) time with path compression.

  • Expected Auxiliary Space Complexity: O(n), as we use a parent array of size 20002 to handle coordinate mapping and a hash set to store unique component roots.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ DFS with Direct Stone Comparison

πŸ’‘ Algorithm Steps:

  1. For each unvisited stone, initiate a depth-first search traversal.

  2. Mark current stone as visited and explore all other stones.

  3. If another stone shares the same row or column, recursively visit it.

  4. Count the number of connected components formed by DFS traversals.

  5. Return total stones minus the number of components found.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nΒ²) - Each stone compared with every other stone

  • Auxiliary Space: πŸ’Ύ O(n) - Visited array and recursion stack

βœ… Why This Approach?

  • Simple and intuitive graph traversal logic

  • No additional data structure overhead beyond visited array

  • Easy to understand connectivity concept

πŸ“Š 3️⃣ BFS with Coordinate Indexing

πŸ’‘ Algorithm Steps:

  1. Create hash maps to store stone indices for each row and column.

  2. For each unvisited stone, perform breadth-first search using a queue.

  3. Explore all stones sharing the current stone's row or column coordinates.

  4. Mark visited stones and add newly discovered stones to the queue.

  5. Count components and calculate maximum removable stones.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— k) - k is average stones per coordinate

  • Auxiliary Space: πŸ’Ύ O(n) - Maps, queue, and visited array

βœ… Why This Approach?

  • Level-order traversal of connected components

  • Efficient coordinate-based stone lookup

  • Avoids redundant pairwise comparisons

πŸ“Š 4️⃣ Union-Find with Map-Based Components

πŸ’‘ Algorithm Steps:

  1. Use hash maps to track component IDs for each row and column.

  2. Assign incremental component IDs as new coordinates are encountered.

  3. When a stone's row and column belong to different components, merge them.

  4. Iterate through all map entries to update merged component IDs.

  5. Count unique final component IDs and return removable stone count.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m) - m is number of unique coordinates

  • Auxiliary Space: πŸ’Ύ O(m) - Maps for coordinate tracking

βœ… Why This Approach?

  • Hash map flexibility for sparse coordinates

  • Direct component ID manipulation

  • No auxiliary parent array needed

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

πŸ”— Union-Find DSU

🟒 O(n Γ— Ξ±(n))

🟒 O(n)

⭐ Optimal with path compression

🎯 Requires DSU understanding

🌳 DFS Direct

🟑 O(n²)

🟒 O(n)

πŸ“– Simple, intuitive logic

🐌 Quadratic time for large inputs

πŸ”„ BFS Indexing

🟒 O(n Γ— k)

🟒 O(n)

🎯 Efficient coordinate lookup

πŸ’Ύ Multiple data structures

πŸ—ΊοΈ Map-Based Union

🟑 O(n Γ— m)

🟒 O(m)

πŸš€ Flexible for sparse data

πŸ”§ Complex merging logic

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Union-Find DSU

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning graph concepts

πŸ₯ˆ DFS Direct

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Large coordinate ranges

πŸ₯‰ BFS Indexing

β˜…β˜…β˜…β˜…β˜†

🎯 Interview/Competitive

πŸ… Union-Find DSU

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated