Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
Example input and output:
>>> reverse_words('this is a string') 'string a is this'
It should be O(N) time and O(1) space (split() and pushing on / popping off the stack are not allowed).
The puzzle is taken from here.
A solution in C/C++:
This should be O(n) in time and O(1) in space.
Edit: Cleaned it up a bit.
The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.