Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using core interview patterns strategy.
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^5Problem summary: 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 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"Leetcode is cool"
"Keep calm and code on"
"To be or not to be"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1451: Rearrange Words in a Sentence
class Solution {
public String arrangeWords(String text) {
String[] words = text.split(" ");
words[0] = words[0].toLowerCase();
Arrays.sort(words, Comparator.comparingInt(String::length));
words[0] = words[0].substring(0, 1).toUpperCase() + words[0].substring(1);
return String.join(" ", words);
}
}
// Accepted solution for LeetCode #1451: Rearrange Words in a Sentence
func arrangeWords(text string) string {
words := strings.Split(text, " ")
words[0] = strings.ToLower(words[0])
sort.SliceStable(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
words[0] = strings.Title(words[0])
return strings.Join(words, " ")
}
# Accepted solution for LeetCode #1451: Rearrange Words in a Sentence
class Solution:
def arrangeWords(self, text: str) -> str:
words = text.split()
words[0] = words[0].lower()
words.sort(key=len)
words[0] = words[0].title()
return " ".join(words)
// Accepted solution for LeetCode #1451: Rearrange Words in a Sentence
struct Solution;
impl Solution {
fn arrange_words(text: String) -> String {
let mut words: Vec<(usize, usize, String)> = text
.split_whitespace()
.enumerate()
.map(|(i, s)| (s.len(), i, s.to_lowercase()))
.collect();
words.sort();
let words: Vec<String> = words.into_iter().map(|(_, _, s)| s).collect();
let mut res = words.join(" ");
res[0..1].make_ascii_uppercase();
res
}
}
#[test]
fn test() {
let text = "Leetcode is cool".to_string();
let res = "Is cool leetcode".to_string();
assert_eq!(Solution::arrange_words(text), res);
let text = "Keep calm and code on".to_string();
let res = "On and keep calm code".to_string();
assert_eq!(Solution::arrange_words(text), res);
let text = "To be or not to be".to_string();
let res = "To be or to be not".to_string();
assert_eq!(Solution::arrange_words(text), res);
}
// Accepted solution for LeetCode #1451: Rearrange Words in a Sentence
function arrangeWords(text: string): string {
let words: string[] = text.split(' ');
words[0] = words[0].toLowerCase();
words.sort((a, b) => a.length - b.length);
words[0] = words[0].charAt(0).toUpperCase() + words[0].slice(1);
return words.join(' ');
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.