MediumNo. 2390

Removing Stars From a String — LeetCode 2390 Python Solution

Pattern
Stack
Topics
Stack, String, Simulation
On a study list
LeetCode 75
Reading time
2 min

The problem

You are given a string s, which contains stars *. In one operation, you can: Choose a star in s.

Example

Input
s = "leet**cod*e"
Output
"lecoe"
Explanation
Performing the removals from left to right:

Python solution

PythonSolution
class Solution:
    def removeStars(self, s: str) -> str:
        ans = []
        for c in s:
            if c == '*':
                ans.pop()
            else:
                ans.append(c)
        return ''.join(ans)

Complexity

Time
O(n)where n is the length of the string s
Space · auxiliary
O(1)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2390. Removing Stars From a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2390. Removing Stars From a String?

LeetCode 2390. Removing Stars From a String is rated Medium on LeetCode.

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

The Python solution on this page runs in O(n), where n is the length of the string s.

What is the space complexity of LeetCode 2390. Removing Stars From a String?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2390. Removing Stars From a String cover?

LeetCode 2390. Removing Stars From a String is tagged Stack, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.