⬅ Previous Topic
K-th Element of Two Sorted ArraysNext Topic ⮕
Find the Largest Odd Number in a Numeric String⬅ Previous Topic
K-th Element of Two Sorted ArraysNext Topic ⮕
Find the Largest Odd Number in a Numeric StringTopic Contents
Given a string s
that contains words separated by spaces, reverse the order of words in the string.
Remove any leading or trailing spaces and reduce multiple spaces between words to a single space in the output.
Note: Do not reverse the characters of individual words—only the word order should be reversed.
s
.def reverse_words(s):
# Trim and split the string
words = s.strip().split()
# Reverse the list of words
words.reverse()
# Join with a single space
return ' '.join(words)
# Sample Input
s = " hello world "
print(reverse_words(s))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Each character in the string is processed once during trimming, splitting, and joining. |
Average Case | O(n) | All operations—trim, split, reverse, and join—are linear with respect to the input size. |
Average Case | O(n) | Even in the worst case with many extra spaces, we still process each character only once. |
O(n)
Explanation: We use extra space to store the list of words and the final result string.
⬅ Previous Topic
K-th Element of Two Sorted ArraysNext Topic ⮕
Find the Largest Odd Number in a Numeric StringYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.