{x}
blog image

Orderly Queue

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.

Solution Explanation for LeetCode 899: Orderly Queue

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:

  1. Check the value of k:

    • If 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.
    • If 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.
  2. Cyclical Permutation (k=1):

    • Initialize ans to the original string s.
    • Iterate from 0 to len(s) - 1 times. In each iteration:
      • Create a new string s by moving the first character to the end.
      • Update ans to be the smaller between ans and s (lexicographically).
  3. Sorting (k > 1):

    • Convert the string s to a character array or list.
    • Sort the array using an efficient sorting algorithm (like merge sort or quicksort, which are typically used by built-in sorting functions). In-place sorting is preferred for efficiency.
    • Convert the sorted array back to a string.

Time and Space Complexity:

  • k = 1:

    • Time Complexity: O(n^2), where n is the length of the string. This is because we iterate through n-1 rotations of the string, each taking O(n) time to create and compare.
    • Space Complexity: O(n), primarily due to the creation of new strings during the rotations. In some implementations, this might be reduced slightly by using in-place manipulation where possible.
  • k > 1:

    • Time Complexity: O(n log n) (due to the sorting). Sorting is the dominant step in this case.
    • Space Complexity: O(n) or O(1) depending on the implementation. In-place sorting would have a space complexity of O(1), while merge-sort based implementations might use O(n) auxiliary space.

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.