Orderly Queue — LeetCode 899 Python Solution

HardMathStringSorting
Problem
#899
Pattern
Sorting
Reading time
2 min

The problem

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.

Example

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".

Python solution

Python
class Solution:
    def orderlyQueue(self, s: str, k: int) -> str:
        if k == 1:
            ans = s
            for _ in range(len(s) - 1):
                s = s[1:] + s[0]
                ans = min(ans, s)
            return ans
        return "".join(sorted(s))

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 899. Orderly Queue is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 899. Orderly Queue?
LeetCode 899. Orderly Queue is rated Hard on LeetCode.
What is the time complexity of LeetCode 899. Orderly Queue?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 899. Orderly Queue?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 899. Orderly Queue cover?
LeetCode 899. Orderly Queue is tagged Math, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview