educative.io

I have a quicker solution

def reverse_words(sentence):
    # Handle some error cases
    if len(sentence) == 0:
        return sentence

    reversed = []

    last_idx = len(sentence) - 1
    lead = last_idx
    trail = last_idx

    # Only do this until we are at the end of the array
    # we will be filling. When trail falls below 0,
    # then we should stop iterating.
    while len(reversed) < len(sentence) and trail > 0:
      # We need two pointers: 1) to find the leading
      # edge of a word, and one to find the trailing
      # edge of a word, and then we can slice the
      # string and put it in the right spot.
      while sentence[lead] == ' ' and lead >= 0:
        #print(lead)
        lead -= 1
      # We have found the start of the first word.
      # Now we need to find the end.
      trail = lead
      while sentence[trail] != ' ' and trail >= 0:
        #print(trail)
        trail -= 1
      # Now the trail points to one past the end of the last
      # word, which could be off the end of the array.

      # Now, we want to use this slice to get the first word
      # Add 1 to the pointers so we don't iterate below a 0
      # index.
      # If we already have a word in here, then add a space between.
      if len(reversed) > 0:
        reversed.append(' ')
        
      reversed.extend(sentence[(trail+1):(lead+1)])
      # We want to update our other pointer to be at this same
      # spot, so it will continue to iterate on the next loop
      # and find the beginning of the next word.
      lead = trail   

    return ''.join(reversed)

Course: Grokking Coding Interview Patterns in Python - Learn Interactively
Lesson: Solution: Reverse Words in a String - Grokking Coding Interview Patterns in Python

Hi @John-Michael_Bradley ,
Thank you for sharing this solution. This solution solves the problem in time complexity O(n) and the solution provided in our lesson is also solving the problem in O(n). Both solution are correct in context of time complexity O(n), you can use any of these according to your ease.

Happy Learning :slight_smile: