LeetCode 2390: Removing Stars From a String Solution

Master LeetCode problem 2390 (Removing Stars From a String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2390. Removing Stars From a String

Problem Explanation

Explanation

To solve this problem, we can iterate through the string from left to right. Whenever we encounter a star, we remove the closest non-star character to its left and the star itself. We repeat this process until there are no more stars left in the string.

  • We can use a stack to keep track of non-star characters encountered so far.
  • When we encounter a star, we pop the top element from the stack because it is the closest non-star character to the left of the star.
  • After iterating through the whole string, we reconstruct the final string using the elements left in the stack.

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity

The space complexity of this solution is also O(n) due to the stack used.

Solution Code

public String removeStars(String s) {
    Stack<Character> stack = new Stack<>();
    
    for (char c : s.toCharArray()) {
        if (c == '*') {
            stack.pop();
        } else {
            stack.push(c);
        }
    }
    
    StringBuilder sb = new StringBuilder();
    while (!stack.isEmpty()) {
        sb.insert(0, stack.pop());
    }
    
    return sb.toString();
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2390 (Removing Stars From a String)?

This page provides optimized solutions for LeetCode problem 2390 (Removing Stars From a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2390 (Removing Stars From a String)?

The time complexity for LeetCode 2390 (Removing Stars From a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2390 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2390 in Java, C++, or Python.

Back to LeetCode Solutions