You are given a string s
that consists of words separated by spaces.
- A word is defined as a sequence of non-space characters.
- Your task is to reverse the order of words in the string.
- Note that extra spaces between words should be reduced to just a single space in the final output, and there should be no leading or trailing spaces.
Here’s the [Problem Link] to begin with.
Examples
Example 1
Input: s = "the sky is blue"
Output: "blue is sky the"
Explanation: Words are reversed in order.
Example 2
Input: s = " hello world "
Output: "world hello"
Explanation: Extra spaces are removed, and words are reversed.
Example 3
Input: s = "a good example"
Output: "example good a"
Explanation: Multiple spaces shrink to one.
Intuition and Approach
This problem requires reversing words while handling spaces properly. The key points are:
- Splitting the string into words:
- Python’s
split()
function splits on whitespace and automatically removes extra spaces. - For example:
" hello world ".split()
→["hello", "world"]
.
- Python’s
- Reversing the list of words:
- Once we have the words in a list, we need to reverse their order.
- For example:
["the", "sky", "is", "blue"]
→["blue", "is", "sky", "the"]
.
- Joining the words back into a single string:
- Use
" ".join(words)
to form the reversed sentence. - Ensures that words are separated by exactly one space.
- Use
Code Implementation
class Solution:
def reverseWords(self, s: str) -> str:
words = s.split() # Step 1: Split string into words, removes extra spaces
res = []
# Step 2: Traverse words in reverse order
for i in range(len(words) - 1, -1, -1):
res.append(words[i])
if i != 0: # Add a space between words
res.append(" ")
# Step 3: Join characters into final string
return "".join(res)
Code Explanation
words = s.split()
- Splits
s
into a list of words. - Removes unnecessary leading, trailing, or multiple spaces.
- Splits
- Reversing with loop:
- Iterates from the last word to the first.
- Adds each word to
res
. - Adds a space
" "
between words (but not after the last word).
"".join(res)
- Joins the list of words and spaces into a single string.
So the sentence gets reconstructed in reversed order with proper spacing.
Dry Run
Input: s = " hello world "
s.split()
→["hello", "world"]
- Loop in reverse:
- Add
"world"
→ res = [“world”] - Add space
" "
→ res = [“world”, ” “] - Add
"hello"
→ res = [“world”, ” “, “hello”]
- Add
"".join(res)
→"world hello"
Final output: "world hello"
Time and Space Complexity
- Time Complexity:
- Splitting the string →
O(N)
- Reversing and joining →
O(N)
Overall: O(N), whereN
is the length of the string.
- Splitting the string →
- Space Complexity:
- Extra space for storing words →
O(N)
- Result array →
O(N)
Overall: O(N)
- Extra space for storing words →
Conclusion
The Reverse Words in a String problem can be efficiently solved by:
- Splitting the string into words (removing extra spaces automatically).
- Reversing the word order.
- Joining them back with exactly one space.
This approach runs in O(N) time and is simple, clean, and highly effective.
This problem is commonly asked in coding interviews to test string manipulation and handling of edge cases like extra spaces.
For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.