mediumStringsPattern: Mixed
Interior Word Reversal Solution
Problem Statement
You are given a sequence of words as a sentence. Reverse the order of all words except the first and last word, and return the modified sentence.
Examples
Example 1:
Input:the dog runs quickly outside
Output:the quickly runs dog outside
Explanation: Reversing the middle words 'dog runs quickly' results in 'quickly runs dog'.
Constraints
- 1 <= sentence length <= 100
- 1 <= word length <= 20
- The input sentence contains only lowercase letters and spaces.
- The input sentence does not start or end with a space.
Time: O(n) Space: O(n)
The optimal approach involves using a two-pointer technique to reverse the middle words in place, then joining the modified words back into a sentence. This approach has a time complexity of O(n) and space complexity of O(n), where n is the number of words in the sentence. It is more efficient as it only requires a single pass through the data.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
words = sys.stdin.readline().strip().split(" ")
first_word = words[0]
last_word = words[-1]
middle_words = words[1:-1]
reversed_middle_words = middle_words[::-1]
result = " ".join([first_word] + reversed_middle_words + [last_word])
print(result)