Length of Last Word

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Length of Last Word

Approach

Traverse from the end, skip trailing spaces, then count contiguous non-space characters.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Reverse Traversal

Why It Works

The last word is exactly the first non-space segment encountered from the end.

Updated Mar 2026