MediumSorting

Rearrange Words in a Sentence

1 approach, code in every language

Problem description

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^5

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free