Start learning free

LESSON 345 OF 674 · TWO POINTERS

Reverse Words in a String

Practice O(n)

You get a string input made of words. The words are separated by single spaces. There is no space at the start or the end.

Return the words in reverse order, still one space apart.

The letters inside each word stay in the same order.

Example 1:

Input:  input = "keep calm and code on"

Output:  "on code and calm keep"

Example 2:

Input:  input = "algorithms"

Output:  "algorithms"
Explanation:  There is only one word.
It stays as it is.

Example 3:

Input:  input = "red fish blue fish"

Output:  "fish blue fish red"
Explanation:  "fish" appears twice.
Each copy counts as its own word.

Constraints:

  • 1 to 10,000 words.
  • At most 100,000 characters in total.
  • Only lowercase English letters and single spaces.
STEP 1 OF 18
    Ctrl + Enter to check