899. Orderly Queue¶ Time: $O(n^2)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16class Solution { public: string orderlyQueue(string s, int k) { if (k > 1) { ranges::sort(s); return s; } string ans = s; for (int i = 1; i < s.length(); ++i) ans = min(ans, s.substr(i) + s.substr(0, i)); return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19class Solution { public String orderlyQueue(String s, int k) { if (k > 1) { char[] chars = s.toCharArray(); Arrays.sort(chars); return String.valueOf(chars); } String ans = s; for (int i = 1; i < s.length(); ++i) { String t = s.substring(i) + s.substring(0, i); if (ans.compareTo(t) > 0) ans = t; } return ans; } } 1 2 3 4class Solution: def orderlyQueue(self, s: str, k: int) -> str: return (''.join(sorted(s)) if k > 1 else min(s[i:] + s[:i] for i in range(len(s))))