InterviewPrepKit

Home / Coding / Stack

Removing Stars From a String

medium Original ↗
Solving tips
  • Recognize '*' targets the most recent surviving letter to its left, which is exactly LIFO: use a stack, push letters and pop on '*'.
  • Scan left to right in one pass with no lookahead; join the stack at the end for the answer.
  • Pitfall: don't build the result with repeated string concatenation or slicing (res[:-1]), which reintroduces O(n^2); use a list as the stack.
  • Target O(n) time and O(n) space; the same idea appears as an in-place two-pointer overwrite in languages with mutable strings.

Problem

You are given a string s containing lowercase letters and * characters. Every * deletes two things at once: the closest non-star character to its left, and the star itself.

Apply this operation for every star (the input is guaranteed to make this always possible — a star always has a letter to its left to erase) and return the string that remains. The result is unique 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; repeated string surgery is too slow.

Think about it first

Hint 1 "Closest non-star character to its left" — which classic data structure hands you the most recently seen item first?
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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.