Orderly Queue - 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.

Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.

Input & Output

Example 1 — k=1 Rotations Only
$ Input: s = "cba", k = 1
Output: "acb"
💡 Note: With k=1, we can only move the first character to the end. Possible rotations: "cba" → "bac" → "acb" → "cba". The lexicographically smallest is "acb".
Example 2 — k≥2 Any Permutation
$ Input: s = "cba", k = 2
Output: "abc"
💡 Note: With k≥2, we can achieve any permutation. The lexicographically smallest permutation is the sorted string "abc".
Example 3 — Already Sorted
$ Input: s = "abc", k = 3
Output: "abc"
💡 Note: The string is already in lexicographically smallest order, so no changes are needed.

Constraints

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

Visualization

Tap to expand
Orderly Queue: Moving Characters to EndInput String:c b ak=1: can move only first chark = 1: Try Rotations"cba" → "bac" → "acb"Best: "acb"k ≥ 2: Sort CharactersAny permutation possibleBest: "abc"Output depends on k value and mathematical properties
Understanding the Visualization
1
Input
String s and integer k representing how many front characters we can move
2
Process
Apply moves optimally based on k value
3
Output
Lexicographically smallest achievable string
Key Takeaway
🎯 Key Insight: When k≥2, any permutation is achievable, so we can simply sort the string
Asked in
Google 25 Facebook 18 Amazon 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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