Make The String Great - 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.

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

Notice that an empty string is also good.

Input & Output

Example 1 — Basic Removal
$ Input: s = "leEeetcode"
Output: "leetcode"
💡 Note: Remove the 'eE' pair: 'e' and 'E' are the same letter but different cases, so we remove both. Result: "leetcode"
Example 2 — Multiple Removals
$ Input: s = "abBAcC"
Output: ""
💡 Note: Remove 'bB' → "aAcC", then remove 'cC' → "aA", finally remove 'aA' → "". Result: empty string
Example 3 — No Removals Needed
$ Input: s = "s"
Output: "s"
💡 Note: Single character has no adjacent pairs to remove. Result: "s"

Constraints

  • 1 ≤ s.length ≤ 100
  • s contains only lowercase and uppercase English letters

Visualization

Tap to expand
Make The String Great INPUT String s = "leEeetcode" l e E e e t c o d e Bad pair! 'e' and 'E' Bad String Rule: Adjacent chars where one is lowercase and other is same letter in uppercase Using Stack: top ... bottom ALGORITHM STEPS 1 Initialize Stack Create empty stack to build result string 2 Iterate Each Char For each character in input string s 3 Check Bad Pair If stack top and current differ by 32 (ASCII) --> Pop stack (remove pair) 4 Push to Stack Else push current char onto the stack Processing "leEeetcode": l --> push [l] e --> push [l,e] E --> pop! [l] (e,E pair) e --> pop! [] (l,? no) FINAL RESULT Output: "leetcode" l e e t c o d e OK Verification: No adjacent bad pairs All same-case neighbors String is now "good" Complexity: Time: O(n) Space: O(n) n = length of string Key Insight: Use a stack to process characters. When current char and stack top form a bad pair (same letter, different case - ASCII difference of 32), pop the stack. Otherwise, push current char. The stack automatically handles cascading removals, ensuring all bad pairs are eliminated in one pass. TutorialsPoint - Make The String Great | Optimal Stack Solution
Asked in
Facebook 15 Amazon 12
94.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen