Monday, October 22, 2012

Interview Question: Reverse words in a sentence

Have you ever been asked this question in a technical interview for a software related position: "Using the language of your choice, reverse the words in a sentence."? If so, have you ever wondered how many solutions in different languages exist? Scripting, object-oriented, functional programming, commands, and the list could go on...

Thanks to Andrew for providing such a short and cool solution that might show why Linux users just love Linux and its tools! You can try this on a Linux terminal: echo "this is the sentence to reverse" | tr ' ' '\n' | tac | tr '\n' ' '; echo

Fyi, tr stands for translate character, which means that it will search for all the ' ' (spaces) and replace them with '\n' (new line); tac prints a file/string in reverse, like the opposite of cat.

Let me know what you think and feel free to share your solutions! 


  1. Python:
    'hello world'[::-1]
    'dlrow olleh'
    much easier :D

    1. Thanks for your solution but as Mariam explained below, the interview question is to reverse the order of the words rather than the letters in the string. Nevertheless, your python solution to reverse the letters in a string is definitely cool! :)

  2. Hi Marly and Andrew,
    That's such a cool linux script :) Thanks for sharing!

    @anonymous: I think that the interview question means to change the order of the words not the letter: eg "Hello world" would be "world hello" :)

    1. Mariam!! Thanks! :)

      Also thanks for the clarification about the question! ;)

  3. So, if the order of the words should be reversed and the result should be a string, I'd go for this in Python:

    ' '.join(SENTENCE.split()[::-1])

    Andreas ;-)

    1. Hey Andreas!

      Thanks for your 2nd solution! :) (I assume that was you too up there, correct me if I am wrong!)

      It's so great to see how many solutions can come up from such a simple question! It also shows the strengths of some languages/tools compared to others.

      Once again thank you so much for sharing your solution! :)

  4. Even shorter: tac --separator=" "

    1. Here's an even shorter one :P
      tac -s' '
      I think this is the shortest answer to date, comes in at 9 characters.