Removing Stars From a String - Stack [JS]

Description 

Solution: Stack

Reverse s, instead of removing the closest to the left, remove the closest to the right.
We can then use a stack to efficiently find and remove the closest non-star on the right.
The top of the stack is the closest non-star on the right.
Whatever is left in the stack are the final characters.

Time Complexity: O(n)
Space Complexity: O(n)

var removeStars = function(s) {
  s = s.split("").reverse();
  let stack = [], n = s.length;
  for (let i = n - 1; i >= 0; i--) {
    if (s[i] === '*') stack.pop();
    else stack.push(s[i]);
  }
  return stack.join("");
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]