Skip to content
UniCircle
EasyCodingStrings and char arrays

Reverse the order of words in a line (in place)

Question C-STR-101

You are given one line of text made of words separated by one or more spaces. Print the words in reverse order, separated by exactly one space.

In C, try to do it in place in the character array (no second array of words): reverse the whole string, then reverse each word back.

Constraints

  • 1 ≤ length of the line ≤ 100000
  • The line contains at least one word.

Input and output

Input
One line of text (letters, digits and punctuation; words are separated by spaces).
Output
The words in reverse order, joined by single spaces.

Examples

Input 1

campus placement drive starts monday

Output

monday starts drive placement campus

The five words come out last-to-first.

Input 2

hello   world

Output

world hello

Three spaces between words become one.

Show hints
  • Reversing the whole line puts the words in the right order but spells each one backwards.
  • A second pass that reverses every word fixes the spelling.
  • Skip runs of spaces when you print, so that only one space separates words.
Show the explanation

Two-reversal trick. Write a helper rev(s, i, j) that swaps characters from both ends of s[i..j] towards the middle.

  1. Trim the trailing newline, then reverse the entire line. "campus placement drive" becomes "evird tnemecalp supmac": the words are now in reverse order, but each is backwards.
  2. Walk the line. Skip spaces, find the end of the next word, reverse just that word, and print it (with one space before every word except the first).

Each character is swapped at most twice, so the work is linear and the only extra memory is a few indices. This is the answer interviewers look for when they say "without extra space". In Python the idiomatic answer is " ".join(line.split()[::-1]). split() with no argument already treats any run of spaces as one separator.

Original UniCircle question. Last reviewed 22 Oct 2026.