Reverse Words in a String - Python Solution

1. Introduction

"Reverse Words in a String" is a common problem in string manipulation, focusing on rearranging the words in a sentence in reverse order. This problem tests the ability to process and manipulate strings, handling spaces correctly, which is a frequent requirement in text processing and formatting tasks.


Given a string s, the task is to reverse the order of the words in the string. Words are defined as sequences of non-space characters, separated by spaces. The output should concatenate these words in reverse order by a single space, removing any leading or trailing spaces and reducing multiple spaces between words to a single space.

2. Solution Steps

1. Trim leading and trailing spaces from the string.

2. Split the string by spaces to get an array of words.

3. Reverse the array of words.

4. Join the words back into a string with a single space separator.

5. Return the resulting string.

3. Code Program

def reverseWords(s):
    return " ".join(reversed(s.strip().split()))

# Example Usage
print(reverseWords("the sky is blue"))       # Output: "blue is sky the"
print(reverseWords("  hello world  "))       # Output: "world hello"
print(reverseWords("a good   example"))      # Output: "example good a"


"blue is sky the"
"world hello"
"example good a"


1. String Trimming: Removes any leading or trailing spaces from the string.

2. Splitting: Breaks the string into words based on spaces, handling multiple spaces correctly.

3. Reversing Words: Reverses the order of the words for the desired output.

4. Joining: Combines the words back into a single string with appropriate spacing.

5. Efficient Solution: Achieves the task with O(n) time complexity, where n is the length of the string.

6. Practical Application: Illustrates common string manipulation techniques used in text processing.