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.
Example 1:
Input: s = "cba", k = 1 Output: "acb" Explanation: In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".
Example 2:
Input: s = "baaca", k = 3 Output: "aaabc" Explanation: In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".
Constraints:
1 <= k <= s.length <= 1000s consist of lowercase English letters.This approach is best when k = 1. Since you can only move the first character to the end, you are only able to produce rotations of the string. Therefore, to find the lexicographically smallest string, you can generate all rotations of the string and find the smallest one.
In this C implementation, rotateString is a helper function to get a rotated version of the string. The main function checks if k > 1 to sort the string. If k == 1, it rotates the string in all possible ways and keeps track of the lexicographically smallest string. The qsort function from the standard library sorts the string when k > 1.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2), where n is the length of the string for k = 1 due to generating all rotations.
When k > 1, Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for holding copies of the string during rotations or sorting.
When k > 1, the problem allows moving any of the top k characters to the end, meaning we can potentially rearrange the entire string. Thus, this is equivalent to sorting the characters in the string to achieve the lexicographically smallest string. This can be directly achieved by sorting the string.
This C solution employs qsort to sort the characters of the string when k > 1. For this approach, when k==1, it is assumed to be handled by another approach since the logic for k=1 isn't applicable here.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for holding the sorted version of the string.
| Approach | Complexity |
|---|---|
| Approach 1: Rotational Minimization | Time Complexity: O(n^2), where n is the length of the string for k = 1 due to generating all rotations. |
| Approach 2: Direct Sorting (Applicable for k > 1) | Time Complexity: O(n log n) due to sorting. |
Orderly Queue -(Amazon): Explanation ➕ Live Coding • codestorywithMIK • 8,547 views views
Watch 9 more video solutions →Practice Orderly Queue with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor