Increasing Decreasing String

Increasing Decreasing String

Given a string s. You should re-order the string using the following algorithm:

  1. Pick the smallest character from s and append it to the result.
  2. Pick the smallest character from s which is greater than the last appended character to the result and append it.
  3. Repeat step 2 until you cannot pick more characters.
  4. Pick the largest character from s and append it to the result.
  5. Pick the largest character from s which is smaller than the last appended character to the result and append it.
  6. Repeat step 5 until you cannot pick more characters.
  7. Repeat the steps from 1 to 6 until you pick all characters from s.

In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.

Return the result string after sorting s with this algorithm.

Example 1:

Input: s = “xxxyyzzzz”

Output: “xyzzyxxzz”

Example 2:

Input: s = “hello”

Output: “ehlol”

Example 3:

Input: s = “aaaaa”

Output: “aaaaa”

Constraints:

  • 1 <= s.length <= 500.
  • s contains only lower-case English letters.

Solution:

By seeing the examples, we are sure that we need to apply sorting techniques to check for the smaller or larger character at each steps and iterate through the whole string at every step untill no steps can be taken further. To simplify the problem we will convert our string to a character array to perform operations on it. We will perform counting of number of similar alphabets present in a string and using this we perform oprations. If any count of a letter in a count array gets exhausted we will ignore it for further operations.

Implemenation:

Java:

class Solution {
    public String sortString(String s) {
        int[] count = new int[26];
        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }
        StringBuilder sb = new StringBuilder();
        while (sb.length() < s.length()) {
            for (int i = 0; i < count.length; i++) {
                if (count[i] != 0) {
                    char character = (char) (i + 'a');
                    sb.append(character);
                    count[i]--;
                }
            }
            for (int i = 25; i >= 0; i--) {
                if (count[i] > 0) {
                    char character = (char) (i + 'a');
                    sb.append(character);
                    count[i]--;
                }
            }
        }
        return sb.toString();
    }
}

Complexity Analysis:

  • Time Complexity: O(n<sup>2</sup>).

  • Space Complaxity: O(n).

Scroll to Top