Skip to content
Problem 557 · LeetCode 557(opens in a new tab)

Reverse Words in a String III

EasyStrings

You are given a sentence s: words made of printable characters, with exactly one space between neighbouring words and no space at either end.

Turn every word around so its letters read backwards, but keep the words in their original order and keep each space where it is. Return the new sentence.

Example 1

Input:  s = "red fox runs"
Output: "der xof snur"
Why:    each word is flipped; the order red, fox, runs stays
2 more examples and the constraints

Example 2

Input:  s = "Go now!"
Output: "oG !won"
Why:    punctuation is part of the word it touches

Example 3

Input:  s = "z"
Output: "z"
Why:    one letter reads the same both ways

Constraints

  • 1 ≤ length of s ≤ 50,000
  • s holds printable ASCII characters
  • Words are split by single spaces; there are no spaces at the start or end
  • s contains at least one word

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split, reverse, joinO(n)
  2. Two pointers per wordO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 charactersVerdict
Split, reverse, joinO(n)
Short and clear; extra copies
Two pointers per wordO(n)
Best; one array, in place

n = length of s. Both are linear; the second makes fewer temporary strings.

Edge cases to test

  • One word. "stressed" gives "desserts": there are no spaces to split on.
  • One-letter words. "a b c" comes back unchanged.
  • Punctuation and digits. "x1! ok" gives "!1x ko": every non-space character belongs to a word.
  • Palindromes. "noon" stays "noon", which hides a bug that skips the swap.

Common mistakes

  • Reversing the whole sentence, which also reverses the order of the words.
  • Forgetting the last word, because no space follows it.
  • Off-by-one on the right end: the last letter of a word is at end − 1, not end.

How to talk through it

  1. 1Clarify. Is it always one space between words? Any spaces at the ends? Is punctuation part of a word?
  2. 2Give the simple version. Split, reverse each word, join. Say it is already O(n).
  3. 3Offer the in-place version. Find each word's ends and swap inward with two pointers; spaces never move.
  4. 4Code it. Mention the copy into a character array where strings cannot change.
  5. 5Test out loud. Run one word, one-letter words, and a word with punctuation.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?