Orderly Queue - Problem

Imagine you have a queue of characters from a string, and you're allowed to make strategic moves to rearrange them. You are given a string s and an integer k. In each move, you can choose one of the first k characters from the current string and move it to the end.

Your goal is to find the lexicographically smallest string possible after performing any number of these moves. Think of it as optimizing a queue where you have limited access to only the first k positions!

Example: If s = "cba" and k = 1, you can only move the first character to the end. Starting with "cba" → "bac" → "acb" → "cba" (cycle), the smallest possible is "acb".

However, if k ≥ 2, you gain much more flexibility and can potentially achieve any permutation of the characters!

Input & Output

example_1.py — Basic case with k=1
$ Input: s = "cba", k = 1
Output: "acb"
💡 Note: With k=1, we can only move the first character to the end. Starting with "cba": move 'c' → "bac", move 'b' → "acb", move 'a' → "cba" (back to start). The lexicographically smallest is "acb".
example_2.py — Case with k≥2
$ Input: s = "baaca", k = 3
Output: "aaabc"
💡 Note: With k=3, we can access the first 3 characters for moves. Since k≥2, we can achieve any permutation of the string. The lexicographically smallest permutation is sorting the characters: "aaabc".
example_3.py — Edge case with single character
$ Input: s = "a", k = 1
Output: "a"
💡 Note: With only one character, no matter what moves we make, the result is always "a".

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ k ≤ s.length
  • s consists of lowercase English letters only

Visualization

Tap to expand
Orderly Queue: Strategic RearrangementCase 1: k ≥ 2 (Flexible)Original: c b aStrategy: Sort charactersResult: a b cTime: O(n log n)Case 2: k = 1 (Limited)Original: c b aTry rotations: cba, bac, acbResult: a c b (smallest)Time: O(n²)OptimalLimitedKey Insightk≥2 enables any permutation through strategic swapping
Understanding the Visualization
1
Analyze Access Level
If k≥2, you have flexible access and can achieve any arrangement
2
Choose Strategy
Flexible access (k≥2): sort alphabetically. Limited access (k=1): try all rotations
3
Apply Transformation
Execute the chosen strategy efficiently
4
Return Result
Return the lexicographically smallest possible string
Key Takeaway
🎯 Key Insight: The value of k determines the power of rearrangement - k≥2 gives unlimited permutation power, while k=1 restricts to rotations only.
Asked in
Google 45 Amazon 32 Microsoft 28 Meta 15
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen