Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
tai
JS Solution: once again, we iterate from the end of the string

tai

Oct 23, 2024

This one was a bit tricky for me because I didn't think of the scenario where you could have two *s next to each other, initially I was using a boolean to keep track of the * as I iterated, but if you have two *s next to each other, this doesn't work. I eventually settled on just counting the *s as I went, and decrementing as I encountered non-star characters, this way you don't need to do any reversing. I don't know why they keep proposing that as a viable solution, I feel like in most interviews you'd get dinged for it, or at least it'd be a strange solution if you're limited to using a stack.

class Solution { removeStars(s) {     // ToDo: Write Your Code Here.     const stack = []     let starCount = 0;     for (let i = s.length - 1; i > -1; i--) {         if (s[i] === '*') starCount++;         else {             if (starCount) starCount--;             else stack.push(s[i]);         }     }     let result = ''     while (stack.length) {         result += stack.pop()     }     return result } }

0

0

Comments
Comments

On this page