call(back)
Algorithms & Data StructureseasySign in to star problems

Reverse Words, Keeping the Spacing

Given a string s made of words and spaces, reverse the order of the words. A word is a maximal run of non-space characters.

The spacing must be preserved exactly: the string keeps its leading spaces, its trailing spaces, and the number of spaces in each gap, in their original positions. Only the words change places.

"the sky is blue"       ->  "blue is sky the"
"  hello   world "      ->  "  world   hello "
"a  bb   ccc"           ->  "ccc  bb   a"

The round starts with the plain version, asks you to write and run your own test cases, then adds the spacing rule and asks about the complexity and about doing it in place.

Hints

Hint 1

Think of the string as alternating tokens: space runs and words. The space runs stay; the words are dealt back in reverse order.

Hint 2

Collect the words in one pass. In a second pass, copy each space run as it is and replace the i-th word with the i-th word from the end.

Topics

Asked at

Similar Problems6