Problem Description
Given a sentence where the first letter is capitalized and words are separated by single spaces, rearrange the sentence so that the words are ordered in increasing order of their lengths. If two words have the same length, their original order is maintained. Additionally, the output sentence should also start with a capital letter, with the rest of the characters in lowercase.
Key Insights
- Split the sentence into words.
- Convert all words to lowercase initially to ease processing.
- Use a stable sort by word length to preserve the original order for words with equal lengths.
- After sorting, capitalize the first letter of the first word before rejoining the words into the final sentence.
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting step, where n is the number of words. Space Complexity: O(n) for storing the list of words.
Solution
The algorithm works by:
- Converting the input sentence to lowercase and splitting it into words.
- Sorting the words using a stable sort with the key being the length of the word. This ensures that words with the same length maintain their original order.
- Capitalizing the first letter of the first word in the sorted list to adhere to the sentence formatting requirement.
- Joining the words back together with a space between them to form the final rearranged sentence.
Data structures used include a list/array to hold the words, and the sorting algorithm is used to reorganize the words by their lengths.