First of all we need to split the string into its constituent words, which we can do using the .split() function on String. It’s surprising how many people don’t realise functions like this exist which mean they are instantly flumoxed.

We then iterate in reverse through the array. We take the length of the array (e.g. the number of words) and count down. This can be tricky due to zero indexing so be careful.

We then append each word to a StringBuilder and add a space. Why StringBuilder? If in theory we were to pass a huge sentence of thousands of words into this method then it would create a ton of objects, which would also make it slower. Take this code sample I’ve just run on my machine:

In this example there are a few requirements considerations. What happens if the String is empty? What happens if there is only one letter? You should ensure you ask this question. I’ve assumed that both are in fact palindromes.

There are multiple approaches to this, but I have gone with this simple solution that involves no extra data structures and only half a run through of the data. We use a loop to iterate through the data; at 0, we check the first character to see if it matches the last character. If it does not, we instantly return false. We then increment i by 1, and check the next letter along, then the next furthest back. This continues until we get halfway, or one less than halfway if it’s an uneven number of letters.