714169. Remove the balls

Medium

Remove the Balls

Summary

The problem is about removing balls from a stack based on certain conditions. The key concepts involved are stacks, data structures, and algorithmic approaches.

Detailed Explanation

The given stack contains balls which need to be removed based on their colors. The colors of the balls can be either red or blue. The problem statement does not specify any specific condition for removing the balls except that it needs to be done in such a way that no two blue balls are together in the final sequence.

To solve this problem, we will use a stack-based approach. We will iterate through all the balls and keep pushing them onto the stack. If we encounter a red ball, we simply push it onto the stack. If we encounter a blue ball, we check if the top of the stack is empty or not. If the stack is empty, we push the blue ball onto the stack. If the stack is not empty and the top element of the stack is blue, we pop all the blue balls from the stack until we find a red ball or the stack becomes empty. Then we push the current blue ball onto the stack.

Here's the step-by-step breakdown of the solution:

  1. Initialize an empty stack.
  2. Iterate through all the balls and for each ball:
    • If the ball is red, push it onto the stack.
    • If the ball is blue, check if the stack is empty or not.
      • If the stack is empty, push the blue ball onto the stack.
      • If the stack is not empty and the top element of the stack is blue, pop all the blue balls from the stack until we find a red ball or the stack becomes empty. Then push the current blue ball onto the stack.

The time complexity for this solution is O(n), where n is the number of balls in the stack. The space complexity is also O(n) as in the worst-case scenario, we might end up pushing all the balls onto the stack.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class RemoveBalls {
    public static void removeBalls(Stack<Integer> stack) {
        while (!stack.isEmpty()) {
            int ball = stack.pop();
            if (ball == 1) { // red ball
                continue;
            }
            while (!stack.isEmpty() && stack.peek() == ball) {
                stack.pop();
            }
            stack.push(ball); // push the blue ball onto the stack
        }
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        // add balls to the stack
        removeBalls(stack);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.