#899
Orderly Queue
HardMathStringSortingString ManipulationSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
When k > 1, we can sort the entire string to get the lexicographically smallest arrangement. For k = 1, we can only rotate, so we need to find the smallest rotation.
⚙️
Algorithm
2 steps- 1Step 1: If k == 1, find the lexicographically smallest rotation by checking all rotations.
- 2Step 2: If k > 1, sort the string and return the sorted string.
solution.py4 lines
1def orderlyQueue(s, k):
2 if k == 1:
3 return min(s[i:] + s[:i] for i in range(len(s)))
4 return ''.join(sorted(s))ℹ
Complexity note: The time complexity is O(n log n) due to sorting the string when k > 1. The space complexity is O(n) because we create a new sorted string.
- 1If k is 1, we can only rotate the string, so we need to find the smallest rotation.
- 2If k is greater than 1, we can sort the string to get the smallest arrangement.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.