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!