Problem 151

Abstract / Summary

Given a sentence, reverse the order of the words and return the new sentence with words separated by a single space.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0151.cpp

class Solution {
public:
    string reverseWords(string s) {
        stringstream text;
        text.str(s);

        string result, word;
        while (text >> word)
        {
            if (!result.empty())
                result = word + ' ' + result;
            else
                result = word;
        }

        return result;
    }
};
18 lines | 366 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (5+ million submissions).

Typical patterns to solve this problem:
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method reverseWords. The method receives a standard C++ string containing a sequence of words separated by whitespace. Its purpose is to produce a new string where the order of the words is reversed while preserving a single space between each word. The algorithm leverages the C++ standard library’s stringstream to tokenize the input and builds the result by prepending each extracted word.

Key Steps

The core logic can be broken down into three distinct operations, each illustrated with the corresponding code fragment.

Tokenization with stringstream

stringstream text;
text.str(s);

A stringstream object named text is created and initialized with the input string s. By feeding the entire input into the stream, the subsequent extraction operator (>>) will automatically split the string on any whitespace characters, handling spaces, tabs, and newlines uniformly.

Iterative Extraction and Prepending

string result, word;
while (text >> word)
{
    if (!result.empty())
        result = word + ' ' + result;
    else
        result = word;
}

Inside a while loop, each word is read from the stream into the variable word. The loop continues until no more tokens are available. For each iteration, the algorithm checks whether result already contains content. If it does, the new word is placed before the existing content, separated by a single space. If result is still empty (i.e., processing the first word), the word is assigned directly without a leading space. This approach constructs the reversed sequence incrementally without requiring an auxiliary container to hold all words.

Returning the Final String

return result;

After all tokens have been processed, the method returns the assembled result string, which now holds the words in reverse order.

Edge Cases Handled

The implementation naturally accommodates several edge conditions due to the behavior of stringstream and the conditional logic used when building result.

When the input string is empty, the stream yields no tokens, the loop body never executes, and result remains an empty string, which is returned directly. This matches the expectation that reversing an empty sequence yields an empty result.

If the input consists solely of whitespace characters, the extraction operator skips over all whitespace and produces no tokens. Consequently, the method again returns an empty string, effectively trimming leading, trailing, and intermediate whitespace.

Multiple consecutive whitespace characters between words are collapsed by the extraction operator, which treats any run of whitespace as a single delimiter. The resulting output contains exactly one space between each reversed word, regardless of the original spacing.

A single-word input bypasses the prepend logic because result is empty on the first iteration. The word is assigned directly, and the loop ends, returning the original word unchanged, which is the correct reversed order for a solitary element.

Performance Optimizations Observed

The algorithm avoids allocating additional containers such as vectors or lists to store intermediate words. By directly prepending each word onto the result string, it eliminates the need for a separate reversal pass. This in-place construction reduces memory overhead and keeps the number of allocations low, especially when the number of words is modest.

The use of stringstream for tokenization provides a concise and efficient means of parsing whitespace-separated tokens without manual character scanning. The extraction operator internally employs optimized parsing routines, which can be faster than a custom loop that examines each character.

Conditional concatenation (if (!result.empty())) ensures that a space character is added only when necessary, preventing the creation of an extra leading space. This small check eliminates the need for post-processing to trim unwanted whitespace, thereby saving an additional pass over the string.

Overall, the method achieves the reversal with a single pass over the input stream and incremental string building, resulting in a streamlined execution path that leverages standard library efficiencies.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of colorful building blocks, and each block has a different word written on it. This code is like a magical robot that picks up those blocks one by one from the very beginning of the row. Every time the robot picks up a new word, it places it down in front of the words it already gathered. If the robot already has a little train of words, it puts a tiny space between the new word and the rest of the group. By the time the robot reaches the end of the line, all the words are sitting in the opposite order from how they started. The first word is now at the very back, and the last word is at the very front.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.81 | σ = 1.25

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# TS Rust Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++ TS
MacJim C++
martianoff Scala
pruthvikp Python
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++, TypeScript
MacJim C++
martianoff Scala
pruthvikp Python
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
zfang399 C++
57 links | 40 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Reverse Words in a String | LeetCode 151 | C++, Java, Python'
Knowledge Center 14 mins
Reverse Words in a String | LeetCode 151 | C++, Java, Python
YouTube video 'Reverse Words in a String | Day 15 Built-in Dequeue| [ July LeetCoding Challenge ] [ Leetcode #151 ]'
Algorithms Made Easy 6 mins
Reverse Words in a String | Day 15 Built-in Dequeue| [ July LeetCoding Challenge ] [ Leetcode #151 ]
YouTube video 'Leetcode 151 | Reverse words in a string | 6th from LC 75 | 90 days SE prep'
Pepcoding 6 mins
Leetcode 151 | Reverse words in a string | 6th from LC 75 | 90 days SE prep
YouTube video 'Reverse Words in a String | LeetCode 151 | Reverse String Word by Word | Multiple Approaches'
Programming Tutorials 12 mins
Reverse Words in a String | LeetCode 151 | Reverse String Word by Word | Multiple Approaches
YouTube video 'Reverse Words in a String - LeetCode 151 - Python #leetcode75'
Deepti Talesra 5 mins
Reverse Words in a String - LeetCode 151 - Python #leetcode75
YouTube video 'Reverse Words in a String | Leet code 151 | Theory explained + Python code'
Sai Anish Malla 3 mins
Reverse Words in a String | Leet code 151 | Theory explained + Python code
YouTube video 'Reverse Words in a String | Leetcode 151 | Live coding session 🔥🔥🔥'
Coding Decoded 9 mins
Reverse Words in a String | Leetcode 151 | Live coding session 🔥🔥🔥
YouTube video '151. Reverse Words in a String | JavaScript | LeetCode | Daily Challenge | Easy Explanation'
LeetCodeWithMonu 8 mins
151. Reverse Words in a String | JavaScript | LeetCode | Daily Challenge | Easy Explanation
YouTube video 'reverse words in a string | reverse words in a string leetcode | leetcode 151 | in-place java'
Naresh Gupta 15 mins
reverse words in a string | reverse words in a string leetcode | leetcode 151 | in-place java
YouTube video '151. Reverse Words in a String - LeetCode - JavaScript'
LeetCodeWithMonu 10 mins
151. Reverse Words in a String - LeetCode - JavaScript
YouTube video '151 || Reverse Words in a String || Leetcode Daily Challenge'
CodeFreaks 14 mins
151 || Reverse Words in a String || Leetcode Daily Challenge
YouTube video 'Reverse Words in a String | LeetCode 151 Explained in JavaScript (Easy & Clean Solution)'
Web Coder Abhishek 3 mins
Reverse Words in a String | LeetCode 151 Explained in JavaScript (Easy & Clean Solution)
YouTube video 'LeetCode 151: Reverse Words in a String | Java Solution | Two-Pointer Approach'
Code Scribbler 4 mins
LeetCode 151: Reverse Words in a String | Java Solution | Two-Pointer Approach
YouTube video 'Daily Leetcode #957: Nov 13, 2022 - 151. Reverse Words in a String'
Programming Live with Larry 7 mins
Daily Leetcode #957: Nov 13, 2022 - 151. Reverse Words in a String
YouTube video 'Leetcode | Top Interview 150 | Medium | 151. Reverse Words in a String  | Javascript'
Software Interviews Prep 14 mins
Leetcode | Top Interview 150 | Medium | 151. Reverse Words in a String | Javascript
YouTube video 'LeetCode 151: Reverse Words in a String | C# Solution | String Manipulation'
Code Scribbler 4 mins
LeetCode 151: Reverse Words in a String | C# Solution | String Manipulation
YouTube video 'Daily Leetcode #106: Jul 15, 2020 - 151. Reverse Words in a String'
Programming Live with Larry 4 mins
Daily Leetcode #106: Jul 15, 2020 - 151. Reverse Words in a String
YouTube video '151. Reverse Words in a String | Leetcode | Strings | Fundamentals'
Coding with Tamilarasan 4 mins
151. Reverse Words in a String | Leetcode | Strings | Fundamentals
YouTube video 'Daily Leetcode #568: Oct 20, 2021 - 151. Reverse Words in a String'
Programming Live with Larry 4 mins
Daily Leetcode #568: Oct 20, 2021 - 151. Reverse Words in a String
YouTube video 'LeetCode 151: Reverse Words in a String | Python Solution | String Manipulation'
Code Scribbler 3 mins
LeetCode 151: Reverse Words in a String | Python Solution | String Manipulation
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 easy 1 medium 16 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality