Similar Problems

Similar Problems not available

Sorting The Sentence - Leetcode Solution

Companies:

  • amazon

LeetCode:  Sorting The Sentence Leetcode Solution

Difficulty: Easy

Topics: string sorting  

Problem statement:

Given a sentence consisting of words separated by spaces, construct a sentence where each word is a separate string, sorted in ascending order of their lengths. Meaning, the shortest word comes first in the output sentence.

Example: Input: "LeetCode is a platform for learning coding" Output: "a is for LeetCode learning platform coding"

Solution:

First, we need to convert the given sentence into a list of words. This can be done by splitting the sentence using the space delimiter.

words = s.split()

Next, we can use the sorted function to sort the words list based on the length of each word. We can pass the len function as a key to the sorted function to specify that we want to sort based on the length.

sorted_words = sorted(words, key=len)

Finally, we can join the sorted_words list into a sentence using the join function, with the space delimiter as the separator.

result = " ".join(sorted_words)

This will give us the desired output sentence. However, there is one more step we need to do - we need to capitalize the first letter of the first word in the sentence. This can be done using string slicing.

result = result[0].upper() + result[1:]

Full Python code:

def sortSentence(s: str) -> str: # Split the sentence into a list of words words = s.split() # Sort the words based on length sorted_words = sorted(words, key=len) # Join the sorted words into a sentence result = " ".join(sorted_words) # Capitalize the first letter of the result sentence result = result[0].upper() + result[1:] return result

Time Complexity:

The time complexity of this solution is O(nlogn), where n is the number of words in the sentence. This is because the sorted function has a time complexity of O(nlogn), where n is the length of the input list.

Space Complexity:

The space complexity of this solution is O(n), where n is the number of words in the sentence. This is because we are storing all the words in a list.

Sorting The Sentence Solution Code

1