Get a free weekly practice problem!

Keep that axe sharp.

× No thanks

You only have free questions left (including this one).

But it doesn't have to end here! Sign up for the 7-day coding interview crash course and you'll get a free Interview Cake problem every week.

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 backward! Your colleagues have handed off the last step to you.

Write a method reverseWords that takes a message as an array of characters and reverses the order of the words in-place.

Why an array of characters instead of a string?

The goal of this question is to practice manipulating strings in place. Since we're modifying the message, we need a mutable type like an array, instead of Java's immutable strings.

For example:

char[] message = { 'c', 'a', 'k', 'e', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 's', 't', 'e', 'a', 'l' }; reverseWords(message); System.out.println(message); // prints: "steal pound cake"

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

We can do this in space. Remember, 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?

Start your free trial!

Log in or sign up with one click to get immediate access to free mock interview questions

Start your free trial!

Log in or sign up with one click to get immediate access to free mock interview questions

time and space!

Hmm, the team used your method to finish deciphering the message. There definitely seems to be a heist brewing, but no specifics on where. Any ideas?

How would you handle punctuation?

Start your free trial!

Log in or sign up with one click to get immediate access to free mock interview questions

Reset editor

Powered by qualified.io

. . .