Problem 557

Abstract / Summary

Reverse the characters in each word of a sentence while keeping the word order the same.

Note

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

Python 0557.py

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(w[::-1] for w in s.split())
3 lines | 114 bytes | submitted September 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (1+ 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 reverseWords method receives a single string s and returns a new string where each word in the original input is reversed in place while preserving the original word order. Words are defined as sequences of characters separated by whitespace. The implementation relies on Python’s built-in string operations to achieve the transformation concisely.

Key Steps

Splitting the Input into Words

The first operation isolates individual words by calling the split method on the input string.

s.split()

split without arguments treats any consecutive whitespace as a delimiter and discards empty results, which means leading, trailing, or multiple internal spaces are automatically normalized. This behavior ensures that the function does not produce spurious empty words and that the output contains a single space between each reversed word.

Reversing Each Word

For every word produced by the split, the code applies slice notation with a step of -1 to obtain the reversed sequence of characters.

w[::-1]

Slice reversal is performed in C-level code inside the Python interpreter, making it faster than a manual loop. The expression is placed inside a generator expression, so each word is reversed on-the-fly without constructing an intermediate list of all reversed words.

Joining the Reversed Words

The reversed words are concatenated back into a single string using the join method with a single space as the separator.

" ".join(...)

join iterates over the generator once, allocating the final string in a single pass. This avoids the overhead of repeated string concatenation and yields a result that matches the original spacing convention (single spaces between words).

Edge Cases Handled

When the input string is empty, split returns an empty list, the generator produces no elements, and join returns an empty string, which correctly reflects the expectation for an empty input.

If the input consists solely of whitespace characters, split again yields an empty list, leading to an empty output string. This behavior eliminates any stray spaces that might otherwise appear.

A single-word input bypasses the need for joining multiple elements; the generator yields one reversed word, and join returns that word directly, preserving the absence of surrounding spaces.

Punctuation and non-alphabetic characters are treated as ordinary characters within a word, so they are reversed along with the surrounding letters. For example, "hello,world" becomes "olleh,dlrow" because the comma remains attached to its original word segment.

Multiple consecutive spaces between words are collapsed by split, so the output contains exactly one space between each reversed word, regardless of how many spaces were present in the original string.

Performance Optimizations

The implementation leverages a generator expression inside join, which means each word is processed and reversed only when needed for concatenation. This lazy evaluation prevents the creation of an intermediate list of reversed words, reducing memory pressure for large inputs.

Slice notation ([::-1]) is executed in compiled code and operates on the underlying string buffer directly, offering a highly efficient reversal mechanism compared to manual character swapping in Python loops.

Using join with a pre-computed separator string performs a single allocation for the final result, avoiding the quadratic cost associated with repeated string concatenation.

Overall, the combination of built-in string methods, lazy generation, and C-level operations yields a solution that is both succinct and performant for typical use cases.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long train made of several colorful blocks. Each block has a word written on it, and all the blocks are linked together in a specific order. The first thing that happens is the train gets taken apart so that every word block is sitting by itself on the floor.

Once the blocks are separated, the code looks at each individual word. Imagine picking up a word like cat and flipping it around until it says tac instead. Every single word in the line gets flipped backward like this while keeping its own special shape.

After all the words are turned around, they get glued back together into one long line exactly like they were before, but now every word is reading from right to left instead of left to right. It is a bit like looking at a row of toys through a mirror where everything appears turned around. The result is a new sentence where every word is spelled backward, but the words are still lined up in the same spots they started in.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 9 | μ = 8.54 | σ = 1.01

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python Rust JS Go PHP TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
fpdjsns C++
halfrost Go
JoshCrozier JS
Krazune C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
Krazune C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
38 links | 23 authors | 11 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

14 solutions   September 13, 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