11. Remove the Balls
✅ GFG solution to the 'Remove the Balls' problem: simulate consecutive removal of matching balls using stack or in-place logic. 🚀
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
You are given two arrays color[] and radius[], representing a sequence of balls:
color[i]denotes the color of the i-th ball.radius[i]denotes the radius of the i-th ball.
👉 If two consecutive balls have the same color and same radius, they are removed. 🧹 This removal process is repeated until no more such adjacent pairs exist.
🧮 Your task is to return the number of balls remaining after all possible removals.
📘 Examples
Example 1
Input:
color[] = [2, 3, 5]
radius[] = [3, 3, 5]
Output:
3
Explanation:
All balls have different properties — no removals possible.Example 2
🔒 Constraints
1 ≤ color.length = radius.length ≤ 10⁵
1 ≤ color[i] ≤ 10⁹
1 ≤ radius[i] ≤ 10⁹
✅ My Approach
We simulate the removal of consecutive equal balls using in-place stack simulation:
Two-Pointer In-Place Simulation
💡 Idea:
Use a variable j as a stack pointer (think of it like the top of a stack):
Traverse through the
color[]andradius[]arrays usingi.At each index
i, check ifcolor[i] == color[j]andradius[i] == radius[j]:If yes, it’s a matching pair — remove both by decrementing
j.If no, move the current ball to the new
jindex (simulate pushing to stack).
Finally, return
j + 1as the number of remaining balls.
📝 Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the number of balls. We traverse the list once and do constant work per step.Expected Auxiliary Space Complexity: O(1), as we only use a few variables and modify the input in-place without extra space.
🧑💻 Code (C++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated