Orderly Queue Problem
Description
LeetCode Problem 899.
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string..
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Example 1:
Input: s = "cba", k = 1
Output: "acb"
Explanation:
In the first move, we move the 1^st character 'c' to the end, obtaining the string "bac".
In the second move, we move the 1^st character 'b' to the end, obtaining the final result "acb".
Example 2:
Input: s = "baaca", k = 3
Output: "aaabc"
Explanation:
In the first move, we move the 1^st character 'b' to the end, obtaining the string "aacab".
In the second move, we move the 3^rd character 'c' to the end, obtaining the final result "aaabc".
Constraints:
- 1 <= k <= s.length <= 1000
- s consist of lowercase English letters.
Solution
Approach: Rotations for k = 1, Sorting Otherwise
The answer depends only on whether k is 1 or larger.
k = 1. Each move takes the first letter and puts it at the end, which rotates the string by one. The strings we can reach are exactly the n rotations of s, so try them all and keep the smallest.
k ≥ 2. Now any arrangement of the letters is reachable, so the answer is s sorted. The reason is that we can swap any two adjacent letters. Treat the string as a circle that we rotate (moving the first letter to the end is always allowed). To swap the adjacent letters x and y:
- Rotate until
xandyare the first two letters:x y …. - Move
y(the second letter) to the end:x … y. - Move
x(now the first letter) to the end:… y x.
In the circle, y and x have traded places and everything else is unchanged. Adjacent swaps can produce any permutation (that is how bubble sort works), so the sorted string is reachable, and nothing is smaller than it. A larger k only gives more choices, so it reaches the same strings.
In Example 2, "baaca" with k = 3 becomes "aaabc", its sorted form.
Complexity: for k = 1, O(n2) time to build and compare the n rotations, and O(n) space. For k ≥ 2, O(n log n) time to sort. n is the length of s.
class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
if k >= 2:
# With two front letters to choose from, any two adjacent letters can be swapped,
# so every arrangement is reachable and the sorted one is the smallest.
return "".join(sorted(s))
# With k == 1 the only reachable strings are the rotations of s.
best = s
for i in range(1, len(s)):
rotation = s[i:] + s[:i]
if rotation < best:
best = rotation
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.