← All Lessons Lesson 23 / 68
Lesson 23

Reverse the Letters in Each Word

Reverse the Letters in Each Word

This problem asks you to take a sentence and flip the letters inside every word — but keep the words sitting in the same places they started.

What "reverse each word" really means

Imagine the sentence is a row of small boxes, and each box holds one word. The order of the boxes never changes. You only spin the letters *inside* each box around so they read backward.

So This becomes sihT, and string becomes gnirts. But the first word is still first, and the last word is still last.

A quick rule of thumb: the words stay put, only their spelling gets reversed.

The catch: spaces must stay exactly the same

Real sentences are messy. The problem warns you about two things:

  • The string might have leading or trailing spaces — extra blank space at the very start or very end.
  • The words might be separated by more than one space — two or three spaces between words instead of just one.

You are not allowed to clean any of this up. Every space, even a run of several spaces in a row, must appear in the output in the exact same place. Think of spaces as walls between words. You reverse the letters between the walls, but you never move, add, or remove a wall.

Walking through the examples

Example 1

Input:  This is a string
Output: sihT si a gnirts

Look at each word on its own:

  • ThissihT
  • issi
  • aa (a single letter reversed is still itself)
  • stringgnirts

The four words are still in the same order. Only the letters flipped.

Example 2

Input:  I love coding
Output: I evol gnidoc
  • II
  • loveevol
  • codinggnidoc

How to think about solving it

A simple plan in plain steps:

  1. Move through the string from left to right.
  2. When you reach the start of a word (a run of non-space letters), find where that word ends.
  3. Reverse just that chunk of letters in place.
  4. Leave every space exactly where it is, then continue scanning until you reach the end.

You are given this starting point to fill in:

using namespace std;
class Solution {
public:
    string reverseWords(string s) {

    }
};

The key idea to hold onto: treat each word as its own little block, reverse the letters inside that block, and never touch the spaces.

Reverse the Letters in Each Word
Diagram — click to zoom (scroll / drag to pan)