InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Removing Stars From a String

medium Original ↗ 00:00

Problem

You are given a string s of lowercase letters and * characters. Each * removes the closest non-star character to its left, and the star itself.

Apply this operation for every star and return the string that remains. The input guarantees every star has a letter to its left to remove. The result is the same regardless of the order in which you process the stars.

Examples

Example 1

Input: s = "leet**cod*e" Output: "lecoe" Explanation: the first * erases the closer t, the second * erases the e before it, and the third * erases d; what remains is lecoe.

Example 2

Input: s = "erase*****" Output: "" Explanation: five stars erase all five letters, leaving the empty string.

Example 3

Input: s = "ab*c*" Output: "a" Explanation: the first star removes b, the second star removes c.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters and *.
  • The operation is always performable. A linear single-pass solution is expected; repeatedly rebuilding the string is too slow.

Think about it first

Hint 1 "Closest non-star character to its left" refers to the most recently seen character. Which data structure returns items in that order?
Hint 2 You never need to look ahead. Scan left to right and decide what each character does to what you've kept so far.
Hint 3 Keep a stack (a Python list) of surviving letters. On a letter, push it; on a `*`, pop once. Join the stack at the end.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug