#1544

Make The String Great

Easy
StringStackStackGreedy
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)

Using a stack allows us to efficiently manage the characters and remove bad pairs in a single pass through the string. This approach is much faster than the brute-force method.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: For each character, check if the stack is not empty and if the top of the stack forms a bad pair with the current character. If so, pop the stack (remove the bad pair).
  4. 4Step 4: If not, push the current character onto the stack.
  5. 5Step 5: At the end, convert the stack back to a string.
solution.py8 lines
1def makeGood(s):
2    stack = []
3    for char in s:
4        if stack and abs(ord(stack[-1]) - ord(char)) == 32:
5            stack.pop()  # Remove the bad pair
6        else:
7            stack.append(char)
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 stack potentially holding all characters in the worst case.

  • 1Using a stack allows us to handle adjacent pairs efficiently.
  • 2The character comparison using ASCII values simplifies the detection of bad pairs.

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