Solving: sentenceReverse


You are given an array of characters arr that consists of sequences of characters separated by space characters. Each space-delimited sequence of characters defines a word.

Implement a function reverseWords that reverses the order of the words in the array in the most efficient manner.


input:  arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', '  ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
output: [ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'e', 'r', 'f', 'e', 'c', 't' ]
  • [input] array.character arr → 0 ≤ arr.length ≤ 100
  • [output] array.character


I like this problem because it illustrates how even perfectly respectable solutions with a clear logic/action plan can still be optimized if we choose to take a look at the problem from a completely different angle. It also shows how useful a single helper function can be for implementing a concept (reverse the order of values in an array) at a macro and micro level (reverse all character to correct the order of the words, then reverse the characters of each word), and finally how a single concept can be used at the macro and micro level to provide an elegant and optimized solution.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store