Program to find a good string from a given string in Python

Suppose we have a string s with lower and upper case English letters. We consider a string is a good string which does not have any two adjacent characters s[i] and s[i + 1] where ?

  • 0 <= i <= size of s - 2

  • s[i] is in lower-case and s[i + 1] is the same letter but in upper-case or vice-versa.

To convert a string into good string, we can select two adjacent characters that make the string bad and remove them. We continue this process until the string becomes good (an empty string can be a good one). We have to find the string after making it good.

So, if the input is like s = "popPpulaBbr", then the output will be "popular", because we first delete either "pP" or "Pp" and then delete "Bb".

Algorithm

To solve this, we will follow these steps ?

  • Create an empty list to store result characters

  • For each character in the string:

    • If the result list is not empty and the last element is the same letter (different case) as current character, remove the last element

    • Otherwise, append the current character to the result list

  • Join all elements in the result list and return the string

Example

Let us see the following implementation to get better understanding ?

def solve(s):
    result = []
    for ch in s:
        if result and result[-1] != ch and result[-1].lower() == ch.lower():
            result.pop()
        else:
            result.append(ch)
    return ''.join(result)

s = "popPpulaBbr"
print("Input:", s)
print("Output:", solve(s))
Input: popPpulaBbr
Output: popular

How It Works

The algorithm uses a stack-like approach:

  • Step 1: Process "p" ? result = ['p']

  • Step 2: Process "o" ? result = ['p', 'o']

  • Step 3: Process "p" ? result = ['p', 'o', 'p']

  • Step 4: Process "P" ? same letter different case, remove last 'p' ? result = ['p', 'o']

  • Step 5: Continue until "Bb" pair is also removed

Another Example

Let's test with a different input ?

def solve(s):
    result = []
    for ch in s:
        if result and result[-1] != ch and result[-1].lower() == ch.lower():
            result.pop()
        else:
            result.append(ch)
    return ''.join(result)

# Test with multiple cases
test_cases = ["abBAcC", "leEeetcode", "s"]

for test in test_cases:
    print(f"Input: {test} ? Output: {solve(test)}")
Input: abBAcC ? Output: 
Input: leEeetcode ? Output: leetcode
Input: s ? Output: s

Conclusion

This problem uses a stack-based approach to remove adjacent characters with the same letter but different cases. The time complexity is O(n) and space complexity is O(n) where n is the length of the string.

Updated on: 2026-03-25T20:19:14+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements