
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
Editorial
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. |
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)