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.
1import java.util.Arrays;
2
3public class OrderlyQueue {
4 public String orderlyQueue(String s, int k) {
5 if (k > 1) {
6 char[] arr = s.toCharArray();
7 Arrays.sort(arr);
8 return new String(arr);
9 }
10 String minString = s;
11 for (int i = 1; i < s.length(); ++i) {
12 String rotated = s.substring(i) + s.substring(0, i);
13 if (rotated.compareTo(minString) < 0) {
14 minString = rotated;
15 }
16 }
17 return minString;
18 }
19
20 public static void main(String[] args) {
21 OrderlyQueue solution = new OrderlyQueue();
22 String s = "cba";
23 int k = 1;
24 System.out.println(solution.orderlyQueue(s, k));
25 }
26}
In this Java code, sorting is applied if k > 1
. For k == 1
, it manually rotates the string by taking substrings and concatenating them, then looks for the minimum lexicographic string among all rotations.
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.
1using System.Linq;
public class OrderlyQueue {
public string OrderlyQueueMethod(string s, int k) {
if (k == 1) { return null; /* This approach doesn't handle k=1 */}
char[] arr = s.ToCharArray();
Array.Sort(arr);
return new string(arr);
}
public static void Main() {
OrderlyQueue solution = new OrderlyQueue();
string s = "baaca";
int k = 3;
Console.WriteLine(solution.OrderlyQueueMethod(s, k));
}
}
In C#, we use Array.Sort()
to sort the string when k > 1
. The assumption is k = 1
is addressed in another part of the solution.