The Remove All Occurrences of a Substring problem repeatedly removes the leftmost occurrence of a given pattern from a string until no more occurrences remain. This medium coding problem uses a stack to construct the result incrementally, detecting the pattern at the top of the stack. The string, simulation, and stack interview pattern is demonstrated.
Goldman Sachs, Microsoft, Meta, Amazon, Google, Bloomberg, and IBM ask this because the efficient approach builds the result as a stack and checks if the last len(part) characters match the pattern — avoiding O(n) string scanning per removal.
Stack-based construction with suffix check. Maintain a stack (or list). For each character of s: append to stack. Check if the last len(part) characters equal part. If yes, pop those characters. Continue until all characters processed.
s="daabcbaabcbc", part="abc".
Remove All Occurrences of a Substring uses the "build and trim" stack pattern: construct the output by appending one character at a time, checking if the tail matches the pattern. This is O(n × len(part)) with no intermediate string creation. Practice similar "stack with pattern detection" problems: "remove comments from code," "evaluate expression with parentheses."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Removing Stars From a String | Medium | Solve | |
| Count Collisions on a Road | Medium | Solve | |
| Resulting String After Adjacent Removals | Medium | Solve | |
| Remove K-Balanced Substrings | Medium | Solve | |
| Clear Digits | Easy | Solve |