Advertisement

Rearrange Words in a Sentence - LeetCode 1451 Solution

Rearrange Words in a Sentence - Complete Solution Guide

Rearrange Words in a Sentence is LeetCode problem 1451, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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. Example 1: Input: text = "Leetcode is cool" Output: "Is cool leetcode" Exp

Detailed Explanation

The problem requires you to rearrange the words in a given sentence such that the words are ordered by their lengths in ascending order. If two words have the same length, their original order in the sentence should be preserved. The input sentence starts with a capital letter, and each word is separated by a single space. The output sentence should also start with a capital letter.

Solution Approach

The solution involves splitting the input sentence into individual words, converting them to lowercase, sorting the words based on their lengths while maintaining the original order for words of the same length, joining the sorted words back into a sentence, and capitalizing the first letter of the resulting sentence.

Step-by-Step Algorithm

  1. Step 1: Convert the input sentence to lowercase and split it into an array (or vector) of individual words using spaces as delimiters.
  2. Step 2: Sort the array of words based on their lengths using a stable sorting algorithm. This ensures that words with the same length maintain their original order.
  3. Step 3: Join the sorted words back into a single string, separated by spaces.
  4. Step 4: Capitalize the first letter of the resulting string (the first word in the rearranged sentence).
  5. Step 5: Return the rearranged sentence.

Key Insights

  • Insight 1: Splitting the sentence into words is crucial for individual manipulation.
  • Insight 2: Using a stable sorting algorithm (like Python's `sorted()` or implementing a stable sort in other languages) ensures the preservation of original word order when lengths are equal.
  • Insight 3: Correctly handling the capitalization of the first letter in the output sentence is a necessary detail.

Complexity Analysis

Time Complexity: O(n log n)

Space Complexity: O(n)

Topics

This problem involves: String, Sorting.

Companies

Asked at: Expedia.