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 - Optimal Solution INPUT String s = "cba" 'c' idx 0 'b' idx 1 'a' idx 2 k=1 zone Input Values: s = "cba" k = 1 Move first k chars to end (rotation) k=1: only rotations ALGORITHM STEPS 1 Check k value k=1: try all rotations 2 Generate rotations Create all n rotations "cba" --> rotate 0 "bac" --> rotate 1 "acb" --> rotate 2 [MIN] (c moved to end twice) 3 Compare strings Find lexicographically min 4 Return minimum 'a' < 'b' < 'c' Time: O(n^2) for k=1 O(n log n) for k>1 (sort) FINAL RESULT Smallest String Found: 'a' 'c' 'b' Output: "acb" OK - Verified! After 2 rotations: cba --> bac --> acb 'acb' is lex smallest among all rotations Key Insight: When k=1, we can only rotate the string. Try all n rotations, return the lexicographically smallest. When k>=2, we can achieve ANY permutation (bubble sort simulation), so just sort the string! TutorialsPoint - Orderly Queue | Optimal Solution
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