1451. Rearrange Words in a Sentence LeetCode Solution

In this guide, you will get 1451. Rearrange Words in a Sentence LeetCode Solution with the best time and space complexity. The solution to Rearrange Words in a Sentence problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Rearrange Words in a Sentence solution in C++
  4. Rearrange Words in a Sentence solution in Java
  5. Rearrange Words in a Sentence solution in Python
  6. Additional Resources
1451. Rearrange Words in a Sentence LeetCode Solution image

Problem Statement of Rearrange Words in a Sentence

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”
Explanation: There are 3 words, “Leetcode” of length 8, “is” of length 2 and “cool” of length 4.
Output is ordered by length and the new first word starts with capital letter.

Example 2:

Input: text = “Keep calm and code on”
Output: “On and keep calm code”
Explanation: Output is ordered as follows:
“On” 2 letters.
“and” 3 letters.
“keep” 4 letters in case of tie order by position in original text.
“calm” 4 letters.
“code” 4 letters.

See also  2867. Count Valid Paths in a Tree LeetCode Solution

Example 3:

Input: text = “To be or not to be”
Output: “To be or to be not”

Constraints:

text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1451. Rearrange Words in a Sentence LeetCode Solution in C++

class Solution:
  def arrangeWords(self, text: str) -> str:
    words = text.split()
    count = collections.defaultdict(list)

    for word in words:
      count[len(word)].append(word.lower())

    c2 = OrderedDict(sorted(count.items()))

    ans = []

    for l in c2:
      for word in c2[l]:
        ans.append(word)

    ans[0] = ans[0].capitalize()

    return ' '.join(ans)
/* code provided by PROGIEZ */

1451. Rearrange Words in a Sentence LeetCode Solution in Java

N/A
// code provided by PROGIEZ

1451. Rearrange Words in a Sentence LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.