
Sponsored
Sponsored
This approach involves splitting the original string into individual words using space as a delimiter, reversing the list of words, and then joining them back together with a single space.
Time Complexity: O(N), where N is the length of the string, as we process each character once.
Space Complexity: O(N), additional space for intermediate and result storage.
1def reverseWords(s: str) -> str:
2 words = s.split()
3 return ' '.join(reversed(words))
4
5input_str = " hello world "
6output_str = reverseWords(input_str)
7print(output_str)The Python solution is concise with split() and reversed() to obtain reversed words and join them together with a space.
This optimized approach manipulates the string in place by using a character array. We'll first reverse the entire string, and then reverse each word to return them to their correct order.
Time Complexity: O(N), where N is the number of characters in the string.
Space Complexity: O(1), as the operation is done in-place without extra space.
1
JavaScript approach includes trimming the string, reversing the entire string, and then dealing with reversals of each individuated word in place for the final output format.