KatInterview

935. Orderly Queue

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

The problem asks for the lexicographically smallest string achievable by repeatedly moving one of the first k characters to the end. The solution depends critically on the value of k.

Solution

Orderly Queue in Python

class Solution:
    def orderlyQueue(self, s: str, k: int) -> str:
        if k > 1:
            # If k > 1, we can achieve any permutation of the string.
            # This is because we can effectively perform adjacent swaps (like in bubble sort).
            # If we can do any permutation, the lexicographically smallest
            # string is simply the sorted version of the original string.
            return "".join(sorted(s))
        else: # k == 1
            # If k == 1, we can only move the first character to the end.
            # This means we can only generate rotations of the string s.
            # We need to find the lexicographically smallest rotation.
            n = len(s)
            smallest = s
            # Check all n-1 other rotations.
            for _ in range(1, n):
                s = s[1:] + s[0] # Perform one rotation.
                if s < smallest:
                    smallest = s
            return smallest

Orderly Queue in Java

class Solution {
    public String orderlyQueue(String s, int k) {
        if (k > 1) {
            // If k > 1, we can achieve any permutation of the string.
            // The argument is that we can effectively perform bubble sort because any
            // adjacent pair of characters can be swapped. This means we can sort the string.
            // The lexicographically smallest string is the sorted version of s.
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        } else { // k == 1
            // If k == 1, we can only move the first character to the end.
            // This is equivalent to generating all cyclic shifts of the string.
            // We need to find the lexicographically smallest one among them.
            String smallest = s;
            // We iterate through all possible n-1 rotations.
            for (int i = 1; i < s.length(); i++) {
                // Perform one rotation.
                s = s.substring(1) + s.charAt(0);
                if (s.compareTo(smallest) < 0) {
                    smallest = s;
                }
            }
            return smallest;
        }
    }
}

Orderly Queue in C++

class Solution {
public:
    string orderlyQueue(string s, int k) {
        if (k > 1) {
            // If k > 1, we can achieve any permutation of the string.
            // The key insight is that with k>1 moves, we can effectively perform
            // a bubble sort. Since any adjacent characters can be swapped, we can
            // achieve any permutation. The lexicographically smallest is the sorted string.
            sort(s.begin(), s.end());
            return s;
        } else { // k == 1
            // If k == 1, we can only move the first character to the end.
            // This generates all cyclic shifts (rotations) of the string.
            // We need to find the lexicographically smallest rotation.
            string smallest = s;
            for (int i = 1; i < s.length(); ++i) {
                // Rotate the string by one position to the left by moving the first char to the end.
                // s = s.substr(1) + s[0]; // This is less efficient due to new string creation
                // std::rotate is an efficient in-place rotation.
                rotate(s.begin(), s.begin() + 1, s.end());
                if (s < smallest) {
                    smallest = s;
                }
            }
            return smallest;
        }
    }
};

Orderly Queue in TypeScript

function orderlyQueue(s: string, k: number): string {
    if (k > 1) {
        // If k > 1, we can achieve any permutation of the string.
        // The reasoning is that with k > 1, we can effectively perform adjacent swaps,
        // which is sufficient to achieve any permutation (like in bubble sort).
        // Thus, the lexicographically smallest string is the sorted version.
        return s.split('').sort().join('');
    } else { // k == 1
        // If k == 1, we can only move the first character to the end.
        // This operation generates all cyclic shifts (rotations) of the string.
        // We must find the lexicographically smallest among all possible rotations.
        let smallest = s;
        // Iterate through all n possible starting points for the string.
        for (let i = 1; i < s.length; i++) {
            // Rotate the string by one position.
            s = s.substring(1) + s.charAt(0);
            if (s < smallest) {
                smallest = s;
            }
        }
        return smallest;
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.