Rearrange Words in a Sentence Problem
Description
LeetCode Problem 1451.
Given a sentence text (A sentence is a string of space-separated words) in the following format:
- First letter is in upper case.
- Each word in
textare separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.
Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"
Constraints:
textbegins with a capital letter and then contains lowercase letters and single space between words.1 <= text.length <= 10^5
Solution
Approach: Stable Sort by Length
Split the text into words and sort them by length. Words of the same length must keep their original order, which is exactly what a stable sort guarantees, so we do not need a tie-breaker on the index.
The capital letter needs care. The first word of the input starts with a capital, but it may not stay first, so lowercase it before sorting (otherwise "Leetcode" would end up in the middle with a capital L). After sorting, join the words with single spaces and uppercase the first character of the result.
Use a stable sort: Python's sort, Java's Arrays.sort on objects, JavaScript's Array.prototype.sort, C++'s stable_sort and Go's sort.SliceStable. C++'s sort and Go's sort.Slice are not stable and can mix up words of equal length.
Complexity: O(n log n) time for the sort, where n is the length of text, and O(n) extra space for the words.
class Solution:
def arrangeWords(self, text: str) -> str:
words = text.split()
words[0] = words[0].lower()
words.sort(key=len) # Python's sort is stable: equal lengths keep their order
ans = " ".join(words)
return ans[0].upper() + ans[1:]