Problem 1544

Abstract / Summary

Remove adjacent pairs of letters that are the same and opposite case until no more such pairs remain.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1544.py

class Solution:
    def makeGood(self, s: str) -> str:
        stack = [ "!" ] # stop marker
        for c in s:
            other = chr(ord(c) ^ 32) # ASCII values of lower-/uppercase letters are 32 apart
                                     # that means they differ by just one bit
            if stack[-1] == other:
                stack.pop()
            else:
                stack.append(c)

        stack.pop(0) # remove stop marker
        return "".join(stack)
13 lines | 483 bytes | submitted November 26, 2023 | GitHub   36% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (600k+ submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method makeGood. The method receives a string s and returns a new string where any adjacent pair of characters that are the same letter in opposite cases (for example, 'a' and 'A') are removed. This removal is performed repeatedly until no such adjacent pair remains. The algorithm uses a stack-like list to process the characters in a single left-to-right pass, achieving the transformation in linear time.

Core Logic

The algorithm begins by initializing a list named stack with a sentinel value "!". This sentinel acts as a stop marker that simplifies boundary checks when the stack is empty.

stack = [ "!" ]  # stop marker

The main loop iterates over each character c in the input string s. For each character, the code computes the counterpart character other that would cancel c if they appear adjacent. This is done by toggling the sixth bit of the ASCII code, which flips the case of an alphabetic character because uppercase and lowercase letters differ by exactly 32 (the value of the sixth bit).

other = chr(ord(c) ^ 32)  # ASCII values of lower-/uppercase letters are 32 apart

After obtaining other, the algorithm checks whether the top element of the stack matches other. If it does, the top element is removed, effectively discarding both the current character and its matching counterpart. If it does not match, the current character is pushed onto the stack.

if stack[-1] == other:
    stack.pop()
else:
    stack.append(c)

When the loop finishes, the sentinel value at the bottom of the stack is removed, and the remaining characters are concatenated to form the result string.

stack.pop(0)  # remove stop marker
return "".join(stack)

Edge Cases Handled

The use of the sentinel value "!" ensures that the algorithm never attempts to access an index that does not exist, even when the first character of the input string could be eliminated. For example, if the input is "aA" the stack initially contains ["!"]. The first character 'a' is pushed, resulting in ["!", "a"]. When the second character 'A' is processed, other becomes 'a', which matches the top of the stack, causing a pop and leaving only the sentinel. After the loop, the sentinel is removed, and the empty string is returned, correctly handling the case where the entire input collapses.

Another edge case involves strings that contain no cancellable pairs, such as "abc" or "ABC". In these situations, the condition stack[-1] == other never becomes true, so each character is simply appended to the stack. The final result is the original string, demonstrating that the algorithm preserves input that does not require modification.

The algorithm also gracefully handles strings that consist solely of the sentinel character "!". Since the sentinel is not part of the input alphabet, it never interferes with the comparison logic, and the final removal of the sentinel yields an empty string, which is the correct output for an empty input.

Performance Considerations

The implementation processes each character exactly once, performing a constant amount of work per character: a bitwise XOR to compute the opposite case, a single comparison, and at most one push or pop operation on the list. Because Python list append and pop from the end are amortized O(1) operations, the overall runtime scales linearly with the length of the input string.

Memory usage is limited to the size of the stack, which never exceeds the length of the input plus one for the sentinel. The stack holds only characters that have not yet been cancelled, so in the worst case (no cancellations) it stores the entire input. This approach avoids the need for auxiliary data structures beyond the stack itself.

The choice of a sentinel value eliminates the need for explicit checks for an empty stack before each comparison, reducing branch overhead and simplifying the loop body. This small optimization contributes to a tighter inner loop, which can be beneficial when processing very large strings.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of magical letter magnets that love to stick to each other. These magnets are special because when an uppercase letter and a lowercase letter of the same shape appear right next to each other, like a big A and a little a, they pop away and vanish.

To tidy them up, imagine building a neat tower of these letter blocks. One by one, letters from a long string are picked up to look at them. Before adding a letter to the top of the tower, it is compared with the letter already resting at the very top. If the new letter and the top letter are the same shape but different sizes, they react to each other, they disappear, and the letter at the top of the tower is taken away. If they do not act like opposites, the new letter is simply placed on top of the tower to wait.

There is a secret marker at the bottom of the tower just to keep the stack steady while building it, which is pulled away once all the letters are checked. Everything left standing in the tower at the very end is gathered together to form a clear, finished line of letters.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.62 | σ = 1.73

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java C++ Go
Progiez Python Java C++
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
FelixFan1122 Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
FelixFan1122 Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
29 links | 19 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 solutions   November 26, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality