educative.io

Reverse words in a string - more concise solution?

    def reverse_words(sentence):
       words = sentence.split()
       return " ".join(words[::-1])

O(n) time and space

Hi @Isaac_Haseley,
Thanks for reaching us with your query!

Your provided solution is correct and concise with the given space and time complexity, but in the chapter “Two Pointers”, we are aiming to provide the solution using two pointers. It is a technique that is useful in many problems, especially linked data structures, e.g., linked lists, graphs, and trees. In this problem, we apply this two-pointer approach to a string. Your given solution is perfect at reversing the words of a string.

If you’ve any other queries, do let us know. Thanks!

1 Like