Given a string of letters, a bad pair is two adjacent characters where one is uppercase and the other is the same letter in lowercase (e.g., 'aA' or 'Zz'). Repeatedly remove all bad pairs. After removal, new adjacent pairs may become bad and must also be removed. A stack handles this naturally: when the top of the stack and the current character differ by exactly 32 in ASCII (the difference between upper and lowercase), they annihilate. Otherwise, push the current character. This is similar to Remove Adjacent Duplicates but with case sensitivity.
The ASCII difference between uppercase and lowercase letters is exactly 32. For example, 'A' is 65 and 'a' is 97. The absolute difference |65 - 97| = 32. This makes it easy to detect bad pairs without checking both cases explicitly. The stack approach processes each character once, comparing it with the top of the stack. If they differ by exactly 32 (same letter, different case), they cancel each other out.
This problem is commonly asked as a follow-up to Remove Adjacent Duplicates, testing whether you can adapt the same pattern to a different matching condition.
This problem tests understanding of character encoding (ASCII values) and stack operations. It is often asked as a warm-up before more complex string manipulation problems. The same pattern of matching adjacent characters with a specific condition appears in problems like Remove All Adjacent Duplicates and basic HTML tag parsing.
Example Input & Output
All removed.
Ee removed.
Single char.
Algorithm Flow
Solution Approach
Remove adjacent pairs where one letter is the uppercase version of the other (like 'aA' or 'Bb') until no such pairs remain. Use a stack: for each character, if it differs from the top of the stack only by case (same letter, different case), pop the stack. Otherwise, push the character.
The ASCII difference between uppercase and lowercase of the same letter is 32. Characters that differ by 32 and are adjacent in the stack annihilate each other.
Time complexity is O(n), space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public String solution(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (!stack.isEmpty() && Math.abs(stack.peek() - ch) == 32) stack.pop();
else stack.push(ch);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) sb.insert(0, stack.pop());
return sb.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
