Just No more free questions left!

Upgrade Now

You're working on a secret team solving coded transmissions.

Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault. The message has been mostly deciphered, but all the words are backwards! Your colleagues have handed off the last step to you.

Write a function reverse_words that takes a string message and reverses the order of the words in-place.

Since strings in Python are immutable, we'll first convert the string into a list of characters, do the in-place word reversal on that list, and re-join that list into a string before returning it. This isn't technically "in-place" and the list of characters will cost additional space, but it's a reasonable way to stay within the spirit of the challenge. If you're comfortable coding in a language with mutable strings, that'd be even better!

For example:

message = 'find you will pain only go you recordings security the into if' reverse_words(message) # returns: 'if into the security recordings you go only pain will you find'

When writing your function, assume the message contains only letters and spaces, and all words are separated by one space.

Are you sure you're operating on the list of characters in-place?

We can do this in time.

If you're swapping individual words one at a time, consider what happens when the words are different lengths. Isn't each swap time in the worst case?

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

time and space. Our space cost comes from converting the message string to a list. If our input was a list, our space cost would be because we'd be using a constant amount of additional space beyond the input.

Hmm, the team used your function to finish deciphering the message. There definitely seems to be a plot brewing, but no specifics on where. The sender seemed to really like Eccles cakes. Any ideas?

How would you handle punctuation?

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

What's next?

RUN
Code execution powered by Qualified.io

. . .