Ctrl K

Words Sorted by Length

Medium
You get a sentence sentence: words of lowercase English letters separated by single spaces. The very first letter of the sentence is uppercase; all others are lowercase. Reorder the words by increasing length. Words of equal length must stay in the order they had in the original sentence. Return the new sentence in the same format: the first letter uppercase, every other letter lowercase, words separated by single spaces.
Example 1
sentence="Green trees grow so tall" → 'So grow tall green trees'

Word lengths are 5, 5, 4, 2, 4. Sorted: "so" (2), then "grow" and "tall" (4, original order), then "green" and "trees" (5). The first word gets the capital letter.

Example 2
sentence="Hi my old pal" → 'Hi my old pal'

"Hi" and "my" have the same length, so they keep their order; the same goes for "old" and "pal".

Example 3
sentence="Bananas are ripe" → 'Are ripe bananas'
Constraints
  • 1 ≤ len(sentence) ≤ 10⁵
  • The first character is an uppercase English letter
  • The other characters are lowercase English letters and single spaces between words
  • No leading or trailing spaces
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAnagram Buckets MediumBiggest Number From Pieces MediumCharacters Grouped by Count MediumA Subsequence of One Word Only MediumLongest Word by Crossing Out Medium
loading Python…
Input
sentence="Green trees grow so tall"
Expected
'So grow tall green trees'

Run checks the first 3 tests in your browser. Submit checks all 121 tests on the server, hidden ones included.