Reverse the order of words in a given sentence (a string of words).
def reverse_words(sentence): # sentence here is a string of words#TODO: Write - Your - Codereturn sentence
import redef reverse_words(sentence):sentence = re.sub(' +', ' ', sentence.strip())sentence = list(sentence)str_len = len(sentence)str_rev(sentence, 0, str_len - 1)start = 0for end in range(0, str_len + 1):if end == str_len or sentence[end] == ' ':str_rev(sentence, start, end - 1)start = end + 1return ''.join(sentence)def str_rev(_str, start_rev, end_rev):while start_rev < end_rev:_str[start_rev], _str[end_rev] = _str[end_rev], _str[start_rev]start_rev += 1end_rev -= 1s = 'Hello World!'print(s)print(reverse_words(s))
The runtime complexity of this solution is linear, .
The memory complexity of this solution is constant, .
The essence of this algorithm is to reverse the words in a string by a two-step method using two pointers, effectively manipulating the string in place. Initially, the entire string is reversed, which correctly repositions the words in reverse order. However, due to this reversal of the string, the corresponding characters of words are also reversed. To correct the order of the characters, iterate through the string, and identify the start and end of each word, considering space as a delimiter between words. Set two pointers at the start and end of the word to reverse the characters within that word. By repeating this process for each word, the method effectively achieves the goal without requiring additional memory.
sentence
, into a list of characters and store it back in sentence
.sentence
and store it in str_len
.str_rev
function to reverse the entire list of characters sentence
.start
pointer start to 0 and iterate over the range from 0 to str_len + 1
using the pointer end
.
str_rev
function with sentence, start
, and end - 1
as arguments.start
to end + 1
.join(sentence)
.Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!