Python 1370.py
class Solution:
def sortString(self, s: str) -> str:
result = ""
freq = defaultdict(int)
for c in s:
freq[c] += 1
alphabet = "".join(sorted(freq))
while len(result) < len(s):
for c in alphabet:
if freq[c] > 0:
result += c
freq[c] -= 1
for c in alphabet[::-1]:
if freq[c] > 0:
result += c
freq[c] -= 1
return result
Difficulty
and has an acceptance rate of about 77% (100k+ submissions).
Typical patterns to solve this problem:
- Counting
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation defines a class with a single method that rearranges the characters of an input string according to a specific alternating order: it repeatedly picks the smallest remaining character, then the largest, and continues this pattern until all characters are consumed. The algorithm relies on a frequency table to keep track of how many times each character still needs to be placed, and it builds the output incrementally.
Frequency Table Construction
The first logical block creates a mapping from each character to the number of times it appears in the input. A defaultdict with an integer default value is used so that each new character starts with a count of zero and can be incremented directly.
freq = defaultdict(int)
for c in s:
freq[c] += 1
This step guarantees that every character in the string is represented exactly once in the dictionary, with its total count ready for the subsequent processing stages.
Sorted Alphabet Generation
After the frequencies are known, the distinct characters are sorted once to obtain a deterministic ordering from smallest to largest according to their Unicode code points. The sorted characters are concatenated into a single string, which serves as the reference order for both forward and reverse traversals.
alphabet = "".join(sorted(freq))
By constructing this ordered string a single time, the algorithm avoids repeated sorting operations inside the main loop, which contributes to a smoother execution path.
Main Loop - Alternating Forward and Reverse Passes
The core of the method is a while loop that continues until the result string reaches the length of the original input. Inside the loop there are two sequential for loops: the first iterates over alphabet in its natural order, and the second iterates over the same characters in reverse order. In each iteration, the algorithm checks whether the current character still has a positive count in the frequency table. If so, the character is appended to the result and its count is decremented.
while len(result) < len(s):
for c in alphabet:
if freq[c] > 0:
result += c
freq[c] -= 1
for c in alphabet[::-1]:
if freq[c] > 0:
result += c
freq[c] -= 1
The forward pass picks the smallest available character, while the reverse pass picks the largest available character. Because the frequency table is updated after each addition, characters that have been exhausted are automatically skipped in subsequent passes.
Edge Cases Handled
When the input string is empty, the frequency table remains empty, the sorted alphabet becomes an empty string, and the while condition is false from the start, causing the method to return an empty result immediately.
If the input consists of a single distinct character repeated many times, the sorted alphabet contains only that character. Both forward and reverse passes will see the same character, but the frequency check ensures that each occurrence is added exactly once per loop iteration until the count reaches zero.
When all characters are already in alphabetical order, the algorithm still follows the alternating pattern, effectively reproducing the same order because the forward pass consumes the characters in their natural sequence and the reverse pass finds no remaining characters to add.
If the input contains characters with non-consecutive Unicode values (for example, a mix of letters and digits), the sorted alphabet respects the global ordering, and the forward and reverse passes correctly navigate across the gaps, always selecting the smallest or largest remaining character according to the defined order.
Performance Optimizations Observed
The use of a defaultdict eliminates the need for explicit existence checks before incrementing counts, allowing constant-time updates during the frequency construction phase.
Sorting the distinct characters only once and storing the result in alphabet prevents repeated sorting work inside the main loop, which would otherwise increase the overall processing time.
The reverse traversal leverages Python’s slice notation alphabet[::-1], which creates a view of the characters in reverse order without constructing a new list, thereby saving memory overhead.
By checking the frequency count before each append, the algorithm avoids unnecessary string concatenations for characters that have already been exhausted, ensuring that each character contributes to the result exactly as many times as it appears in the input.
The termination condition len(result) < len(s) guarantees that the loop stops precisely when all characters have been placed, avoiding any extra iterations once the frequency table is empty.
Overall, the method balances clarity with efficient use of built-in data structures, delivering a solution that scales well with the size of the input string while adhering to the required alternating ordering logic.
ELI5 - Simplified Explanation
Imagine having a big box filled with lots of colorful letter blocks. The goal is to line them up in a very specific dance. First, the code looks at all the letters in the box and makes a little list to count how many of each color are inside.
Next, it creates a special alphabet line, arranging all the unique letter types in order from first to last. Now the fun part begins because the code starts walking down that line of letters. It looks for each letter one by one, picking them up if it finds them in the box and moving them into a new row. Once it reaches the end of the alphabet, it turns around and walks backward, picking up any remaining letters in reverse order. It keeps marching back and forth like a busy ant until every single letter from the box has been moved into the new, orderly row. The letters are now perfectly arranged thanks to this little back and forth dance.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | JS | Go | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | Java | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | Java | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 451: Sort Characters By Frequency
Solved On The Same Day
- problem 1380: Lucky Numbers in a Matrix
- problem 1310: XOR Queries of a Subarray
- problem 1328: Break a Palindrome
- problem 1343: Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality