educative.io

Educative

Is this a simpler solution?

I just finished implementing a solution for this problem, but it’s a bit different than the recommended approach.

def reverse_words(sentence):
  reversed_sentence = ""
  for word in reversed(sentence.split()):
    reversed_sentence += f"{word.strip()} "
  return reversed_sentence.rstrip()

This solution also seems to have O(n) time and space complexity while being much simpler. Is there a reason the recommended solution seems more complicated? Is it just to illustrate the “two pointers” approach? Or am I missing some other part of the problem here?

1 Like

Hi @dip_n_dots,

Thank you for sharing this solution with us. We have analyzed your solution and, indeed, your solution takes O(n) time and space complexity. The solution you have provided is also simpler than the one that is provided on our platform.

You have used Python’s in-built reverse() function to reverse the string. Internally, Python’s reverse() function uses the two pointers technique to reverse strings. That means, using the in-built reverse() function will have no negative affect on our solution as we have also used the two pointers technique to reverse the string. However, the purpose of the course is to sharpen one’s problem solving skills and not broaden one’s understanding of the in-built functions of a specific language. The reason behind implementing the entire solution from scratch and not using the in-built functions is so that one can deepen their understanding of the problem and solution.

Have an amazing experience learning on Educative!

1 Like