Python 0899.py
class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
# brute forcing test data showed that if k > 1 then s will be sorted
if k > 1:
return "".join(sorted(s))
# and if k == 1 then s will be rotated
result = s
high, low = max(s), min(s)
if high == low:
return s # only one letter that is repeated
for i in range(len(s)):
if s[i] == low:
rotated = s[i:] + s[:i]
result = min(result, rotated)
return result
Difficulty
and has an acceptance rate of about 67% (100k+ submissions).
Typical patterns to solve this problem:
- Math
- Sorting
- 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 provided implementation solves the “orderly queue” problem by distinguishing two distinct regimes based on the value of k. When k exceeds one, the algorithm leverages the fact that any permutation of the string can be achieved, and therefore returns the characters in sorted order. When k equals one, only rotations of the original string are possible; the code searches for the lexicographically smallest rotation. The solution includes early exits for trivial inputs, such as strings composed of a single repeated character.
Key Steps
Handling the case k > 1
The first conditional branch checks whether more than one character can be moved to the front in a single operation. In this scenario the algorithm reduces the problem to sorting the characters, because any ordering can be constructed through a sequence of allowed moves.
if k > 1:
return "".join(sorted(s))
The use of Python’s built-in sorted function provides a concise and efficient way to obtain the characters in ascending lexical order, and join assembles them back into a string.
Early return for a uniform string
Before entering the rotation logic, the code determines the highest and lowest characters present in the input. If both extremes are identical, the string consists of a single repeated character, and no further processing is required.
high, low = max(s), min(s)
if high == low:
return s
This check prevents unnecessary iteration when the result is already known.
Searching for the minimal rotation when k == 1
When only one character may be moved to the front, the algorithm must consider every rotation that begins with the smallest character in the string. It initializes the result with the original string and iterates over each index, constructing a rotation only when the character at that position matches the previously identified minimum.
result = s
for i in range(len(s)):
if s[i] == low:
rotated = s[i:] + s[:i]
result = min(result, rotated)
return result
By restricting rotation generation to positions containing the minimal character, the algorithm avoids creating every possible rotation, which would be unnecessary work.
Edge Cases Addressed
The implementation explicitly handles the situation where the input string contains only one distinct character. In that case high and low are equal, triggering an immediate return of the original string. This covers inputs such as "aaaa" or "bbbbbb".
When k is greater than one, the algorithm does not need to examine the content of the string beyond sorting, which naturally accommodates empty strings (though the problem constraints typically guarantee a non-empty input) and strings of any length.
For k == 1, the code correctly processes strings where the smallest character appears multiple times. By evaluating each occurrence, it ensures that the globally minimal rotation is selected, even when several rotations share the same leading character.
Performance Optimizations
The solution incorporates several optimizations that reduce unnecessary work:
- Built-in sorting: Leveraging
sorteddelegates the heavy lifting to a highly optimized C implementation, avoiding a manual sorting routine. - Early exit for uniform strings: Detecting that all characters are identical eliminates the need for any iteration or rotation generation.
- Selective rotation generation: Instead of generating all
nrotations, the loop creates a rotation only when the current character equals the minimum character. This can dramatically cut the number of constructed strings when the minimum character is rare. - In-place comparison: The use of
min(result, rotated)updates the best candidate without storing an auxiliary list of rotations, keeping memory usage low.
These choices collectively ensure that the algorithm runs quickly for both large inputs with k > 1 and for the more constrained rotation case when k == 1.
ELI5 - Simplified Explanation
Imagine you have a row of colorful letter blocks sitting on a table. The goal of this game is to try and arrange these blocks so that the letters are in alphabetical order, just like a dictionary. You have a special tool called k.
If your tool is strong enough, which happens when k is bigger than one, you can reach inside the row, pick up any block you want, and move it anywhere else. Because you can pick up any block at any time, you can easily put all the blocks in the perfect order from a to z. It is like having magic hands that can sort everything perfectly.
If your tool is weak, which happens when k is exactly one, you have to follow a strict rule. You can only take the block from the very front of the line and move it to the very back of the line. You keep doing this over and over again to see if you can find a way to make the row of letters look as tidy as possible. Since you cannot move the blocks freely, you just rotate the whole line around until the very best version appears at the front. You check every single possible rotation and keep whichever one looks the smallest and neatest.
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Go | Python | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1535: Find the Winner of an Array Game
- problem 1335: Minimum Difficulty of a Job Schedule
- problem 1799: Maximize Score After N Operations
- problem 2088: Count Fertile Pyramids in a Land
- problem 2218: Maximum Value of K Coins From Piles
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