LeetCode 1451: Rearrange Words in a Sentence Solution
Master LeetCode problem 1451 (Rearrange Words in a Sentence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we need to rearrange the words in the sentence based on their lengths in increasing order. If two words have the same length, we need to maintain their original order. The approach involves splitting the sentence into words, sorting the words based on their lengths, and then joining them back into a new sentence.
- Split the given sentence into words.
- Create a custom comparator to sort the words based on their lengths.
- Sort the words using the custom comparator.
- Join the sorted words to form the rearranged sentence.
Time Complexity: O(n log n) where n is the number of words in the sentence. Space Complexity: O(n) where n is the number of words in the sentence.
Solution Code
import java.util.*;
class Solution {
public String arrangeWords(String text) {
String[] words = text.toLowerCase().split(" ");
Arrays.sort(words, (a, b) -> a.length() - b.length());
String result = String.join(" ", words);
return Character.toUpperCase(result.charAt(0)) + result.substring(1);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1451 (Rearrange Words in a Sentence)?
This page provides optimized solutions for LeetCode problem 1451 (Rearrange Words in a Sentence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1451 (Rearrange Words in a Sentence)?
The time complexity for LeetCode 1451 (Rearrange Words in a Sentence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1451 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1451 in Java, C++, or Python.