#1910
Remove All Occurrences of a Substring
MediumStringStackSimulationStackString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a stack-like approach allows us to build the result string character by character. This way, we can efficiently check if the last characters match the substring 'part' and remove them if they do, avoiding multiple passes over the string.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty list (acting as a stack) to build the result.
- 2Step 2: Iterate through each character in 's'.
- 3Step 3: Append each character to the stack.
- 4Step 4: Check if the last characters in the stack match 'part'. If they do, remove them from the stack.
- 5Step 5: Convert the stack back to a string and return it.
solution.py8 lines
1def removeOccurrences(s: str, part: str) -> str:
2 stack = []
3 part_length = len(part)
4 for char in s:
5 stack.append(char)
6 if ''.join(stack[-part_length:]) == part:
7 del stack[-part_length:]
8 return ''.join(stack)ℹ
Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the storage of characters in the stack.
- 1Removing a substring can create new opportunities for removal, so a single pass may not be sufficient.
- 2Using a stack allows us to efficiently manage the characters and check for the substring in a single traversal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.