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.
1using System;
2using System.Linq;
3
4public class OrderlyQueue {
5 public string OrderlyQueueMethod(string s, int k) {
6 if (k > 1) {
7 char[] arr = s.ToCharArray();
8 Array.Sort(arr);
9 return new string(arr);
10 }
11 string minString = s;
12 for (int i = 1; i < s.Length; ++i) {
13 string rotated = s.Substring(i) + s.Substring(0, i);
14 if (string.Compare(rotated, minString) < 0) {
15 minString = rotated;
16 }
17 }
18 return minString;
19 }
20
21 public static void Main() {
22 OrderlyQueue solution = new OrderlyQueue();
23 string s = "cba";
24 int k = 1;
25 Console.WriteLine(solution.OrderlyQueueMethod(s, k));
26 }
27}
This C# solution also applies the concept of sorting when k > 1
and iterates through all rotations for k == 1
to find the smallest string possible by continuously comparing rotated strings.
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 JavaScript solution employs split()
, sort()
, and join()
to sort the string characters if k > 1
. Handling of k = 1
is assumed to be done elsewhere.