Problem

You are given a string s. Reorder 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.

Examples

Example 1:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
Input:
s = "rat"
Output:
 "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.

Solution

Method 1 – Counting and Two-Pointer Simulation

Intuition

The key idea is to simulate the process by repeatedly picking the smallest and then the largest available characters, using a frequency array to efficiently track which characters remain. This allows us to build the answer in the required order without repeatedly sorting.

Approach

  1. Count the frequency of each character in the string (assuming lowercase English letters).
  2. While the result’s length is less than the input’s length:
    • Traverse from ‘a’ to ‘z’, appending each available character and decrementing its count.
    • Traverse from ‘z’ to ‘a’, appending each available character and decrementing its count.
  3. Repeat until all characters are used.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    string sortString(string s) {
        vector<int> cnt(26, 0);
        for (char c : s) cnt[c - 'a']++;
        string ans;
        int n = s.size();
        while (ans.size() < n) {
            for (int i = 0; i < 26; ++i) {
                if (cnt[i]) {
                    ans += (char)('a' + i);
                    cnt[i]--;
                }
            }
            for (int i = 25; i >= 0; --i) {
                if (cnt[i]) {
                    ans += (char)('a' + i);
                    cnt[i]--;
                }
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def sortString(s string) string {
    cnt := make([]int, 26)
    for _, c := range s {
        cnt[c-'a']++
    }
    ans := make([]byte, 0, len(s))
    for len(ans) < len(s) {
        for i := 0; i < 26; i++ {
            if cnt[i] > 0 {
                ans = append(ans, byte('a'+i))
                cnt[i]--
            }
        }
        for i := 25; i >= 0; i-- {
            if cnt[i] > 0 {
                ans = append(ans, byte('a'+i))
                cnt[i]--
            }
        }
    }
    return string(ans)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public String sortString(String s) {
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) cnt[c - 'a']++;
        StringBuilder ans = new StringBuilder();
        int n = s.length();
        while (ans.length() < n) {
            for (int i = 0; i < 26; ++i) {
                if (cnt[i] > 0) {
                    ans.append((char)('a' + i));
                    cnt[i]--;
                }
            }
            for (int i = 25; i >= 0; --i) {
                if (cnt[i] > 0) {
                    ans.append((char)('a' + i));
                    cnt[i]--;
                }
            }
        }
        return ans.toString();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    fun sortString(s: String): String {
        val cnt = IntArray(26)
        for (c in s) cnt[c - 'a']++
        val ans = StringBuilder()
        val n = s.length
        while (ans.length < n) {
            for (i in 0..25) {
                if (cnt[i] > 0) {
                    ans.append('a' + i)
                    cnt[i]--
                }
            }
            for (i in 25 downTo 0) {
                if (cnt[i] > 0) {
                    ans.append('a' + i)
                    cnt[i]--
                }
            }
        }
        return ans.toString()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def sortString(self, s: str) -> str:
        cnt: list[int] = [0] * 26
        for c in s:
            cnt[ord(c) - ord('a')] += 1
        ans: list[str] = []
        n: int = len(s)
        while len(ans) < n:
            for i in range(26):
                if cnt[i]:
                    ans.append(chr(ord('a') + i))
                    cnt[i] -= 1
            for i in range(25, -1, -1):
                if cnt[i]:
                    ans.append(chr(ord('a') + i))
                    cnt[i] -= 1
        return ''.join(ans)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
impl Solution {
    pub fn sort_string(s: String) -> String {
        let mut cnt = [0; 26];
        for b in s.bytes() {
            cnt[(b - b'a') as usize] += 1;
        }
        let n = s.len();
        let mut ans = Vec::with_capacity(n);
        while ans.len() < n {
            for i in 0..26 {
                if cnt[i] > 0 {
                    ans.push((b'a' + i as u8) as char);
                    cnt[i] -= 1;
                }
            }
            for i in (0..26).rev() {
                if cnt[i] > 0 {
                    ans.push((b'a' + i as u8) as char);
                    cnt[i] -= 1;
                }
            }
        }
        ans.into_iter().collect()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    sortString(s: string): string {
        const cnt: number[] = Array(26).fill(0);
        for (const c of s) cnt[c.charCodeAt(0) - 97]++;
        let ans: string[] = [];
        const n = s.length;
        while (ans.length < n) {
            for (let i = 0; i < 26; ++i) {
                if (cnt[i]) {
                    ans.push(String.fromCharCode(97 + i));
                    cnt[i]--;
                }
            }
            for (let i = 25; i >= 0; --i) {
                if (cnt[i]) {
                    ans.push(String.fromCharCode(97 + i));
                    cnt[i]--;
                }
            }
        }
        return ans.join("");
    }
}

Complexity

  • ⏰ Time complexity: O(n*26) — Each character is appended once, and for each round we may scan all 26 letters.
  • 🧺 Space complexity: O(n) — For the answer and the frequency array.