Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Make The String Great

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1544" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. Example 1: 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". Example 2: Input: s = "abBAcC" Output: "" Explanation: We have many possible scenarios, and all lead to the same answer. For example: "abBAcC" --> "aAcC" --> "cC" --> "" "abBAcC" --> "abBA" --> "aA" --> "" Example 3: Input: s = "s" Output: "s" Constraints: 1 <= s.length <= 100 s contains only lower and upper case English letters.

Explanation

Here's the breakdown:

  • Core Idea: Use a stack to simulate the string reduction process. Push characters onto the stack. If the top of the stack and the current character form a "bad pair", pop the character from the stack; otherwise, push the current character onto the stack.
  • Iteration: Process the input string character by character, updating the stack based on the "good string" condition.
  • Result: The final stack content (converted back to a string) will be the "good string".

  • Complexity: O(n) runtime, O(n) storage

Code

    def makeGood(s: str) -> str:
    stack = []
    for char in s:
        if stack and abs(ord(char) - ord(stack[-1])) == 32:
            stack.pop()
        else:
            stack.append(char)
    return "".join(stack)

More from this blog

C

Chatmagic blog

2894 posts