You are given a sentence: a single-space separated string of words where the first word starts with a capital letter. Rearrange the words in ascending order of their length. When two words have the same length, keep them in their original relative order.
Return the resulting sentence with only the first letter capitalized and every other letter in lowercase.
Example 1
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Lengths are is (2), cool (4), leetcode (8), so the order becomes "is cool leetcode" and the first letter is capitalized.
Example 2
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Sorting by length gives on (2), and (3), then keep, calm, code (all 4) preserved in their original order.
Constraints
text begins with a capital letter and then contains lowercase letters and single spaces between words.1 <= text.length <= 10^5See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI