Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Strings

Reverse Words in a String

Medium · Strings · Asked at Amazon, Microsoft, Adobe, TCS, Infosys

Reverse the order of the words in a line. The line may have leading, trailing or multiple spaces; the output must have single spaces between words and no extra spaces.

Input

One line of text with at least one word.

Output

The words in reverse order, separated by single spaces.

Constraints

Example 1

Input

the sky is blue

Output

blue is sky the

Example 2

Input

  hello world  

Output

world hello

Hints

  1. Split the line into words, ignoring any number of spaces between them.
  2. Then output the words from last to first joined by a single space.

Approach

Splitting on whitespace drops the empty pieces caused by leading, trailing or repeated spaces. In C++ a stringstream with >> does it, in Python split() with no argument, in Java trim().split("\\s+"). Reverse the list of words and join them with single spaces.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string line, w;
    getline(cin, line);
    stringstream ss(line);
    vector<string> words;
    while (ss >> w) words.push_back(w);
    for (int i = (int)words.size() - 1; i >= 0; i--) cout << words[i] << (i > 0 ? " " : "\n");
    return 0;
}

Python solution

words = input().split()
print(" ".join(reversed(words)))

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] words = sc.nextLine().trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) sb.append(words[i]).append(i > 0 ? " " : "");
        System.out.println(sb);
    }
}

Solve Reverse Words in a String online · All practice problems