Given a sentence text
(A sentence is a string of space-separated words) in the following format:
text
are 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:
text
begins with a capital letter and then contains lowercase letters and single space between words.1 <= text.length <= 10^5
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to rearranging words involves trying every possible order and combination. We explore all permutations of the words and check each one to see if it meets the sentence's length constraint. This is like trying every single possible arrangement until we find the correct one.
Here's how the algorithm would work step-by-step:
import itertools
def rearrange_words_brute_force(text):
words = text.split()
shortest_length = float('inf')
shortest_word = None
for word in words:
if len(word) < shortest_length:
shortest_length = len(word)
shortest_word = word
possible_arrangements = list(itertools.permutations(words))
valid_arrangements = []
for arrangement in possible_arrangements:
# Check if the first word in the arrangement is the shortest.
if len(arrangement[0]) == shortest_length:
valid_arrangements.append(arrangement)
best_arrangement = None
# Store the length to avoid recalculating.
best_arrangement_length = float('inf')
for arrangement in valid_arrangements:
current_length = 0
is_sorted = True
for word in arrangement:
if len(word) < current_length:
is_sorted = False
break
current_length = len(word)
#We save only the arrangement with the smallest words
if is_sorted:
arrangement_length = sum(len(word) for word in arrangement)
if arrangement_length < best_arrangement_length:
best_arrangement = arrangement
best_arrangement_length = arrangement_length
if best_arrangement:
return ' '.join(best_arrangement)
else:
return text
The best way to rearrange the words is to sort them based on their lengths first. Then, we rebuild the sentence word by word, ensuring that shorter words come before longer ones, capitalizing the first word and converting the rest to lowercase.
Here's how the algorithm would work step-by-step:
def rearrange_words_in_sentence(text):
words = text.lower().split()
# Sort words by their lengths
words.sort(key=len)
# Capitalize the first word
first_word = words[0]
words[0] = first_word[0].upper() + first_word[1:]
# Join the words back into a sentence
rearranged_sentence = ' '.join(words)
return rearranged_sentence
Case | How to Handle |
---|---|
Empty input string | Return an empty string to avoid processing null or empty input |
Input string with only spaces | Trim leading/trailing spaces and return an empty string if only spaces remain |
Input string with a single word | Capitalize the first letter of the word and return it |
Input string with multiple words of the same length | Maintain original order of words having equal lengths during sorting |
Input string with leading or trailing spaces between words | Trim extra spaces between words after splitting into words to ensure correct word length calculation |
Very long input string containing many words, potential memory issues | Use efficient data structures and algorithms to minimize memory consumption |
Input string with punctuation marks attached to words | Remove or handle punctuation marks before word length calculation and sorting |
Input string with mixed case words | Convert all words to lowercase except for the first word after rearrangement |