Tutorialspoint
Problem
Solution
Submissions

Reverse the Words in a Sentence

Certification: Basic Level Accuracy: 63.16% Submissions: 57 Points: 10

Write a Python program that reverses the order of words in a given sentence while preserving the order of characters within each word.

Example 1
  • Input: sentence = "Hello World Python"
  • Output: "Python World Hello"
  • Explanation:
    • Step 1: Split the input sentence into individual words.
    • Step 2: Reverse the order of the words.
    • Step 3: Join the words back together with spaces.
    • Step 4: Return the new sentence with reversed word order.
Example 2
  • Input: sentence = "Coding is fun"
  • Output: "fun is Coding"
  • Explanation:
    • Step 1: Split the input sentence into individual words ["Coding", "is", "fun"].
    • Step 2: Reverse the order of the words ["fun", "is", "Coding"].
    • Step 3: Join the words back together with spaces.
    • Step 4: Return the new sentence with reversed word order.
Constraints
  • 0 ≤ len(sentence) ≤ 10^6
  • Words are separated by a single space
  • No leading or trailing spaces in the input
  • Time Complexity: O(n) where n is the length of the input sentence
  • Space Complexity: O(n) for storing the result
StringsControl StructuresCapgeminiSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Split the sentence into words: words = sentence.split()
  • Reverse the list of words: words = words[::-1]
  • Join the words back with spaces: result = ' '.join(words)

Steps to solve by this approach:

 Step 1: Handle edge cases - empty strings or strings with only whitespace.

 Step 2: Split the input sentence into individual words using the split() method.
 Step 3: Reverse the order of words in the resulting list.
 Step 4: Join the reversed words back together with spaces.
 Step 5: Return the sentence with words in reverse order.

Submitted Code :