Skip to main content
LeetCode 151, Medium. Topics: Two Pointers, String. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

Problem

Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space.

Examples

Constraints

  • 1 <= s.length <= 10^4
  • s contains English letters (upper-case and lower-case), digits, and spaces ’ ’.
  • There is at least one word in s.
Follow up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

AlgoMaster 75.
Last modified on August 25, 2026