Taro Logo

Increasing Decreasing String

#7 Most AskedEasy
Topics:
StringsGreedy Algorithms

You are given a string s. Reorder the string using the following algorithm:

  1. Remove the smallest character from s and append it to the result.
  2. Remove the smallest character from s that is greater than the last appended character, and append it to the result.
  3. Repeat step 2 until no more characters can be removed.
  4. Remove the largest character from s and append it to the result.
  5. Remove the largest character from s that is smaller than the last appended character, and append it to the result.
  6. Repeat step 5 until no more characters can be removed.
  7. 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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are all characters lowercase letters, so a fixed alphabet of twenty-six letters is enough?
  2. If a letter appears more than once, may any remaining copy be taken when that letter is chosen?
  3. Must the result use every character of the original text, with none added or dropped?
  4. Should a pass skip a letter whose copies are already exhausted?
  5. Is a descending pass still required after an ascending pass that may have taken the last copies?

Brute Force Solution

Approach

This simulation counts how many times each lowercase letter appears. It then repeatedly takes one remaining copy of each letter from a to z, then one remaining copy from z to a. It stops when the built text is as long as the original text.

Here's how the algorithm would work step-by-step:

  1. Count the occurrences of each of the twenty-six lowercase letters.
  2. Start an empty result and remember the original length.
  3. While the result is shorter than the original text, run an ascending pass.
  4. In that pass, append one copy of each letter from a to z that still has a remaining count, and decrease that count.
  5. Then run a descending pass from z back to a with the same take-one rule.
  6. Repeat both passes until every original character has been appended.
  7. Join the appended letters into the final text.

Code Implementation

class Solution:
    def sortString(self, input_string: str) -> str:
        character_counts = [0] * 26
        for char in input_string:
            character_counts[ord(char) - ord('a')] += 1

        result_list = []
        total_characters = len(input_string)

        # Loop until every character from the original string has been placed in the result.
        while len(result_list) < total_characters:

            # This ascending pass picks the smallest available characters in increasing order.
            for index in range(26):
                if character_counts[index] > 0:
                    result_list.append(chr(ord('a') + index))
                    character_counts[index] -= 1

            # This descending pass is necessary to pick the largest available characters.
            for index in range(25, -1, -1):
                if character_counts[index] > 0:
                    result_list.append(chr(ord('a') + index))
                    character_counts[index] -= 1

        # After all passes, the list of characters must be joined into the final string.
        return "".join(result_list)

Big(O) Analysis

Time Complexity
O(n) – Counting the letters scans the text once, which is linear in its length. Each later pass inspects a fixed alphabet of twenty-six letters, so one pair of passes is constant work relative to the text length. Every pair of passes appends at least one character while any characters remain, so the number of pairs is at most the text length. Multiplying a linear number of passes by a fixed alphabet yields linear work. The total is O(n).
Space Complexity
O(n) – The count table has twenty-six entries no matter how long the text is. The result stores one character for every input character, so it grows linearly. A few loop indexes sit beside those structures. No extra copy of the windows or subsets is kept. Auxiliary space is therefore dominated by the result and is O(n).

Optimal Solution

Approach

This version also starts from letter counts rather than from repeated searches through the raw text. It drains those counts with an ascending pass and a descending pass, appending one available letter at a time. The result is complete when its length matches the input length.

Here's how the algorithm would work step-by-step:

  1. Build a count for each lowercase letter by scanning the input once.
  2. Prepare an empty list of chosen characters.
  3. Continue while that list is shorter than the input.
  4. Append the smallest remaining letters by walking the alphabet upward and decrementing each count that is used.
  5. Append the largest remaining letters by walking the alphabet downward with the same rule.
  6. Stop once the list length equals the input length.
  7. Join the list into a single string.

Code Implementation

def sort_string(input_string):
    character_counts = [0] * 26
    for character in input_string:
        character_counts[ord(character) - ord('a')] += 1

    result_characters = []
    total_characters = len(input_string)

    # The loop must continue until all characters from the input have been placed in the result.
    while len(result_characters) < total_characters:
        # First pass: Ascending order from 'a' to 'z'.
        for character_index in range(26):
            if character_counts[character_index] > 0:
                result_characters.append(chr(ord('a') + character_index))
                character_counts[character_index] -= 1

        # Second pass: Descending order from 'z' to 'a'.
        for character_index in range(25, -1, -1):
            if character_counts[character_index] > 0:
                result_characters.append(chr(ord('a') + character_index))
                character_counts[character_index] -= 1
    
    # The list of characters is joined to form the final sorted string.
    return "".join(result_characters)

Big(O) Analysis

Time Complexity
O(n) – The initial count is a single pass over the input. After that, the original text is never scanned again. Each ascending or descending walk touches twenty-six counts, which is constant relative to the input length. At least one character is appended whenever characters remain, so there are at most n walks. Constant work per walk across at most n walks is O(n).
Space Complexity
O(n) – Twenty-six counts take constant space. The chosen characters are stored until they can be joined, and there is one of them per input character. Joining those characters produces the returned string, which is required output rather than extra search state. Temporary indexes do not grow with the input. The extra space that scales with the input is O(n).

Edge Cases

The text is a single character
How to Handle:
Return that character, because the first ascending pass takes it and nothing remains.
Every character is the same letter
How to Handle:
Alternate that letter between the ascending and descending passes until its count is exhausted.
The text is already strictly increasing
How to Handle:
The first ascending pass emits every character and the descending pass adds nothing.
Some letters are already used up in the middle of a pass
How to Handle:
Skip any letter whose remaining count is zero and continue with the next letter in that direction.
The text repeats several distinct letters the same number of times
How to Handle:
Each full pair of passes emits two copies of every remaining letter until the counts run out.
0/19 completed