Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2:
Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 104s contains English letters (upper-case and lower-case), digits, and spaces ' '.s.Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine looking at a sentence written backward and wanting to flip the order of the words while cleaning up any messy spaces. The brute force strategy involves going through the text from right to left, picking out each word one by one, and placing them in a brand new line in that reversed order.
Here's how the algorithm would work step-by-step:
def reverse_words_brute_force(input_string): collected_words = [] string_length = len(input_string) pointer_index = string_length - 1 # Traverse backwards to isolate words from right to left while ignoring extra spacing while pointer_index >= 0: if input_string[pointer_index] == ' ': pointer_index -= 1 continue end_of_word = pointer_index while pointer_index >= 0 and input_string[pointer_index] != ' ': pointer_index -= 1 extracted_word = input_string[pointer_index + 1:end_of_word + 1] collected_words.append(extracted_word) # Join the reversed words with a single space to clean up any messy original padding final_reversed_sentence = ' '.join(collected_words) return final_reversed_sentenceInstead of trying to move entire words around while dealing with messy extra spaces, the optimal approach cleans up the text and flips the entire sentence backward. Afterward, it simply goes through the flipped text to restore each individual word back to its correct orientation.
Here's how the algorithm would work step-by-step:
class Solution:
def reverseWords(self, original_string: str) -> str:
# Convert string to list of characters because Python strings are immutable.
char_list = []
string_length = len(original_string)
pointer = 0
while pointer < string_length and original_string[pointer] == ' ':
pointer += 1
while pointer < string_length:
if original_string[pointer] != ' ':
if char_list and char_list[-1] != ' ':
char_list.append(original_string[pointer])
elif char_list and char_list[-1] == ' ':
char_list.append(original_string[pointer])
else:
char_list.append(original_string[pointer])
elif char_list and char_list[-1] != ' ':
char_list.append(' ')
pointer += 1
if char_list and char_list[-1] == ' ':
char_list.pop()
# Reverse the entire character array to place words in the correct reverse order.
left_index = 0
right_index = len(char_list) - 1
while left_index < right_index:
char_list[left_index], char_list[right_index] = char_list[right_index], char_list[left_index]
left_index += 1
right_index -= 1
# Reverse each individual word back to normal orientation while maintaining word order.
word_start = 0
array_length = len(char_list)
for word_end in range(array_length + 1):
if word_end == array_length or char_list[word_end] == ' ':
sub_left = word_start
sub_right = word_end - 1
while sub_left < sub_right:
char_list[sub_left], char_list[sub_right] = char_list[sub_right], char_list[sub_left]
sub_left += 1
sub_right -= 1
word_start = word_end + 1
return "".join(char_list)| Case | How to Handle |
|---|---|
| String with leading or trailing spaces | Trimming operations or pointer adjustments ignore these extraneous spaces during word extraction. |
| Multiple consecutive spaces between words | Split or parsing logic treats multiple spaces as a single delimiter to prevent empty tokens. |
| String containing only spaces | The algorithm filters out empty strings and returns an empty result cleanly. |
| Single word with no spaces | The input is returned as-is after stripping any accidental boundary whitespace. |
| Extremely large string with thousands of words | Linear time complexity ensures efficient memory usage and execution without hitting performance bottlenecks. |
| String with special characters or punctuation attached to words | Characters are treated as part of the word tokens and preserved in their relative positions. |