Skip to main content

Reverse Words in a Sentence

easy
StringTwo PointersTwo Pointer Partition
Asked atAmazonMicrosoftGoogle

Problem Description

Given a string `text` containing words separated by single spaces, return a new string with the words in reversed order.

The input will not have leading or trailing spaces, and there will be exactly one space between consecutive words.

**Example 1:**
```
Input: text = "hello world foo"
Output: "foo world hello"
```

**Example 2:**
```
Input: text = "coding is fun"
Output: "fun is coding"
```

Constraints

  • 1 <= text.length <= 10^4
  • text contains only lowercase English letters and single spaces
  • No leading or trailing spaces
  • Exactly one space between words

Follow-up

Can you solve it in-place using O(1) extra space (beyond the output) by reversing individual characters as well?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.