Sponsored
Sponsored
This approach is best when k = 1
. Since you can only move the first character to the end, you are only able to produce rotations of the string. Therefore, to find the lexicographically smallest string, you can generate all rotations of the string and find the smallest one.
Time Complexity: O(n^2), where n is the length of the string for k = 1 due to generating all rotations.
When k > 1, Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for holding copies of the string during rotations or sorting.
1function orderlyQueue(s, k) {
2 if (k > 1) {
3 return s.split('').sort().join('');
4 }
5 let minString = s;
6 for (let i = 1; i < s.length; i++) {
7 let rotated = s.slice(i) + s.slice(0, i);
8 if (rotated < minString) {
9 minString = rotated;
10 }
11 }
12 return minString;
13}
14
15let s = "cba";
16let k = 1;
17console.log(orderlyQueue(s, k));
This JavaScript code addresses the problem similarly: sorting the string when k > 1
and checking every string rotation to determine the minimal string when k == 1
.
When k > 1
, the problem allows moving any of the top k
characters to the end, meaning we can potentially rearrange the entire string. Thus, this is equivalent to sorting the characters in the string to achieve the lexicographically smallest string. This can be directly achieved by sorting the string.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for holding the sorted version of the string.
1
This Python solution sorts the list of characters when k > 1
using the sorted()
function. When k == 1
, another solution should be applied.