Make The String Great (LeetCode 1544): Solution and Explanation
Delete neighbouring letters that are the same letter in opposite cases, such as aA or Bb, until none are left. For leEeetcode the answer is leetcode, and abBAcC shrinks to the empty string.
Intuition
Removing one bad pair can create another: in abBA, deleting bB makes a and A neighbours. Rescanning from the start after every deletion works but repeats a lot of work.
Read left to right and keep the letters that have survived so far. The survivors never contain a bad pair, so a new letter can only clash with the last survivor.
The last survivor is the top of a stack. If the new letter is its case twin, pop it and drop the new letter; otherwise push the new letter.
Approach: Stack of surviving letters
- Create an empty stack.
- For each letter
ch: if the stack is not empty and the top differs fromchonly by case, pop the top. - Otherwise push
ch. - Join the stack from bottom to top and return it.
Step-by-step example
s = "leEeetcode"
- Push
l, thene. Stack:le. Eis the uppercase twin of the tope, so pop. Stack:l.- Push
e: the top isl, a different letter. Stack:le. - Push
e: same letter and same case as the top, which is allowed. Stack:lee. - Push
t,c,o,d,e; none of them is a case twin of the top. - The stack reads
leetcode, which is the answer.
Code: Python, Java, C++
1class Solution:
2 def makeGood(self, s: str) -> str:
3 stack = []
4 for ch in s:
5 # same letter, opposite case: codes differ by exactly 32
6 if stack and abs(ord(stack[-1]) - ord(ch)) == 32:
7 stack.pop()
8 else:
9 stack.append(ch)
10 return "".join(stack)1class Solution {
2 public String makeGood(String s) {
3 StringBuilder stack = new StringBuilder();
4 for (char ch : s.toCharArray()) {
5 int n = stack.length();
6 if (n > 0 && Math.abs(stack.charAt(n - 1) - ch) == 32) {
7 stack.deleteCharAt(n - 1);
8 } else {
9 stack.append(ch);
10 }
11 }
12 return stack.toString();
13 }
14}1class Solution {
2public:
3 string makeGood(string s) {
4 string stack;
5 for (char ch : s) {
6 if (!stack.empty() && abs(stack.back() - ch) == 32) {
7 stack.pop_back();
8 } else {
9 stack.push_back(ch);
10 }
11 }
12 return stack;
13 }
14};Time and space complexity
O(n)
Each letter is pushed at most once and popped at most once.
O(n)
If no pair ever cancels, the stack holds every letter.
Other approaches
Repeated scan and delete (time O(n^2), space O(n))
Scan for the first bad pair, remove it, and scan again until a full pass finds nothing. Fine for 100 characters but quadratic in general.
Write pointer in place (time O(n), space O(1) extra)
Use a character array as the stack with a write index. A twin of the character before the index moves the index back; anything else is written at the index.
Common mistakes
- Treating two equal letters in the same case, like
ee, as a bad pair. Only opposite cases cancel. - Comparing with
toLowerCasealone, which also matchesee. You need both the same letter and different characters, or a code difference of exactly 32. - Only checking the original neighbours instead of the stack top, which misses pairs that form after a removal.
Frequently asked questions
Why does a code difference of 32 identify a bad pair?
In ASCII each uppercase letter is exactly 32 below its lowercase form, and the input has letters only, so a difference of 32 happens only for the same letter in opposite cases.
Does it matter which bad pair is removed first?
No. The problem states the answer is unique, and the stack removes pairs as soon as they meet, which is one valid order.
How is this related to Remove All Adjacent Duplicates in String?
It is the same stack pattern with a different rule for what cancels: there equal letters cancel, here opposite-case twins do.