Make The String Great — LeetCode 1544 Python Solution

EasyStackString
Problem
#1544
Pattern
Stack
Reading time
2 min

The problem

Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.

Example

Input
s = "leEeetcode"
Output
"leetcode"
Explanation
In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

Python solution

Python
class Solution:
    def makeGood(self, s: str) -> str:
        stk = []
        for c in s:
            if not stk or abs(ord(stk[-1]) - ord(c)) != 32:
                stk.append(c)
            else:
                stk.pop()
        return "".join(stk)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1544. Make The String Great is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1544. Make The String Great?
LeetCode 1544. Make The String Great is rated Easy on LeetCode.
What is the time complexity of LeetCode 1544. Make The String Great?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1544. Make The String Great?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1544. Make The String Great cover?
LeetCode 1544. Make The String Great is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview