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 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st 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 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".
Constraints:
1 <= k <= s.length <= 1000
s
consist of lowercase English letters.This problem asks to find the lexicographically smallest string that can be obtained by repeatedly moving one of the first k
characters to the end of the string. The solution hinges on a crucial observation about the relationship between k
and the achievable string orderings.
Core Idea:
The approach uses case-by-case analysis based on the value of k
:
k = 1
: When only the first character can be moved, we can only generate a cyclical permutation of the original string. We iterate through all these permutations, keeping track of the lexicographically smallest one.
k > 1
: If we can move more than one character, we can effectively swap any two adjacent characters. This means we can sort the string in ascending order to get the lexicographically smallest result.
Algorithm:
Check the value of k
:
k
equals 1, proceed with the cyclical permutation approach. Iterate through all possible rotations of the string s
, comparing each rotation to find the lexicographically smallest.k
is greater than 1, simply sort the string's characters in ascending order. This is feasible because the ability to move multiple characters allows for arbitrary swaps of adjacent characters, enabling sorting.Cyclical Permutation (k=1):
ans
to the original string s
.len(s) - 1
times. In each iteration:
s
by moving the first character to the end.ans
to be the smaller between ans
and s
(lexicographically).Sorting (k > 1):
s
to a character array or list.Time and Space Complexity:
k = 1
:
k > 1
:
Code Examples (Python):
class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
if k == 1:
ans = s
for i in range(len(s) - 1):
s = s[1:] + s[0]
if s < ans:
ans = s
return ans
else:
return "".join(sorted(s))
This Python code directly implements the described algorithm. Other languages (Java, C++, JavaScript, etc.) would follow a similar structure, with differences in syntax and possibly the specific sorting algorithm used. The core logic remains the same, however.