The actually coding of this problem is simple: for the K=1 case, keep rotating the first letter of the string to the back, and return the lowest rotation. For K>=2, then the result is just the sorted string. This is easy to implement, but recognizing this is the difficult part of the problem.
The key insight is that it is possible to swap any two letters in the string when K>=2. Assume that we have the string ***AB****, where * are arbitrary letters that we don't care about for this example. It is possible to get ***BA****, where A and B have swapped places.
We start by constantly moving the first of the letter of the string back, until we get:
**AB*****
*AB******
AB*******
At this point, we can move B, the second letter in the string, to the back of the string.
A*******B
We can then move A to the back of the string:
*******BA.
We can then keep moving the first letter of the string back until the BA pair is in the proper position:
******BA*
*****BA**
****BA***
***BA****
After n swaps, we have now successfully swapped two adjacent letters. Now that we have the ability to swap any two adjacent letters, we can just run bubble sort to get a sorted list. Any case of K > 2 just boils down to the K=2 case, just with the potential to use less moves. This is a very slow way to get to the sorted result, but it is a simple proof that the sorted result is possible. We can then use a much more efficient sorting algorithm in the actual code.
O(n) space
O(nlog(n)) time
On Saturday, June 27, 2020 at 9:12:39 AM UTC-7, Daryl Wang wrote: