Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Increasing Decreasing String

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1370" 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

You are given a string s. Reorder the string using the following algorithm: Remove the smallest character from s and append it to the result. Remove the smallest character from s that is greater than the last appended character, and append it to the result. Repeat step 2 until no more characters can be removed. Remove the largest character from s and append it to the result. Remove the largest character from s that is smaller than the last appended character, and append it to the result. Repeat step 5 until no more characters can be removed. Repeat steps 1 through 6 until all characters from s have been removed. If the smallest or largest character appears more than once, you may choose any occurrence to append to the result. Return the resulting string after reordering s using this algorithm. Example 1: Input: s = "aaaabbbbcccc" Output: "abccbaabccba" Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc" After steps 4, 5 and 6 of the first iteration, result = "abccba" First iteration is done. Now s = "aabbcc" and we go back to step 1 After steps 1, 2 and 3 of the second iteration, result = "abccbaabc" After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba" Example 2: Input: s = "rat" Output: "art" Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm. Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters.

Explanation

Here's a breakdown of the solution:

  • Character Frequency: Maintain a frequency count of each character in the input string. This allows us to efficiently determine the smallest/largest available characters.
  • Iterative Reordering: Iteratively build the reordered string, alternating between ascending and descending character selection as described in the algorithm.
  • Frequency Update: After appending a character to the result, decrement its count in the frequency map.

  • Time Complexity: O(n), where n is the length of the string.

  • Space Complexity: O(1), as the character frequency map has a fixed size (26).

Code

    def reorder_string(s: str) -> str:
    """
    Reorders the string according to the given algorithm.
    """

    counts = {}
    for char in s:
        counts[char] = counts.get(char, 0) + 1

    result = ""
    ascending = True

    while len(result) < len(s):
        if ascending:
            last_char = ''
            for char in sorted(counts.keys()):
                if last_char == '' or char > last_char:
                    if counts[char] > 0:
                        result += char
                        counts[char] -= 1
                        last_char = char


        else:
            last_char = ''
            for char in sorted(counts.keys(), reverse=True):
                if last_char == '' or char < last_char:
                    if counts[char] > 0:
                        result += char
                        counts[char] -= 1
                        last_char = char

        ascending = not ascending

        # Clean up empty counts, otherwise it will lead to infinite loops
        keys_to_remove = []
        for char in counts:
          if counts[char] == 0:
            keys_to_remove.append(char)

        for key in keys_to_remove:
          del counts[key]


    return result

More from this blog

C

Chatmagic blog

2894 posts