Leetcode 1451: Rearrange Words in a Sentence

grid47
grid47
Exploring patterns and algorithms
Jun 14, 2024 8 min read

Given a sentence consisting of space-separated words, rearrange the words in the sentence such that they are ordered by increasing length. Words with the same length should retain their original order. The first word of the rearranged sentence must start with a capital letter, and all other words must be in lowercase.
Problem
Approach
Steps
Complexity
Input: The input is a single string, `text`, representing the sentence. The first letter of `text` is capitalized, and all subsequent letters are lowercase, with words separated by a single space.
Example: Input: text = 'Sorting is fun'
Constraints:
• 1 <= text.length <= 10^5
• The sentence starts with a capital letter.
• Words are separated by a single space.
Output: A string representing the rearranged sentence where words are ordered by their length, starting with a capitalized first word. Words of equal length retain their original order.
Example: Output: 'Is fun sorting'
Constraints:
• The output must preserve the capitalization of the first word and lowercase all other words.
• Words of the same length must retain their original order.
Goal: Rearrange the words in the input sentence by their lengths, ensuring formatting and order constraints are maintained.
Steps:
• Split the input sentence into individual words.
• Normalize the case of the words, converting all to lowercase except the first word.
• Pair each word with its length and its original index.
• Sort the words by their length. If two words have the same length, retain their original order using the index.
• Reconstruct the sentence, capitalizing the first word and separating words with a single space.
Goal: Conditions that must be met for the input and output.
Steps:
• The sentence must contain only alphabetic characters and spaces.
• The first word starts with an uppercase letter, and all subsequent words start with lowercase letters.
Assumptions:
• The input string is valid and conforms to the constraints.
• Words are separated by exactly one space with no trailing or leading spaces.
Input: Input: text = 'Coding is challenging'
Explanation: Output: 'Is coding challenging'. The words are ordered by their lengths: 'is' (2), 'coding' (6), 'challenging' (11).

Input: Input: text = 'Sorting can be hard'
Explanation: Output: 'Be can hard sorting'. Words are ordered by length: 'be' (2), 'can' (3), 'hard' (4), 'sorting' (7).

Input: Input: text = 'A quick brown fox jumps'
Explanation: Output: 'A fox quick brown jumps'. Words are ordered as: 'A' (1), 'fox' (3), 'quick' (5), 'brown' (5), 'jumps' (5). The order of equal-length words is preserved.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus