#2696

Minimum String Length After Removing Substrings

Easy
StringStackSimulationStackSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a stack to efficiently manage the removal of substrings. By pushing characters onto the stack and checking for 'AB' or 'CD' at the top, we can remove them in constant time, leading to a linear time complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: Push the character onto the stack. If the last two characters in the stack form 'AB' or 'CD', pop them off.
  4. 4Step 4: Continue this until all characters are processed.
  5. 5Step 5: The remaining characters in the stack represent the final string.
solution.py8 lines
1def min_length_after_removal(s):
2    stack = []
3    for char in s:
4        stack.append(char)
5        if len(stack) >= 2 and (stack[-1] == 'B' and stack[-2] == 'A' or stack[-1] == 'D' and stack[-2] == 'C'):
6            stack.pop()
7            stack.pop()
8    return len(stack)

Complexity note: The time complexity is O(n) because we traverse the string once, and each character is pushed and popped from the stack at most once. The space complexity is O(n) due to the stack storing the characters.

  • 1Using a stack allows for efficient removal of adjacent substrings in constant time.
  • 2The problem can be visualized as a series of operations that modify the string dynamically.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.