Skip to content
LEETFLIX

Length of Last Word

EasyString
Solve on LeetCode

Easy · scan from the right. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 58. Length of Last Word. The copyrighted prompt is on LeetCode. This page is a working scan from the right for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

s =
Hello World

Output

5

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Skip trailing spaces, then count

Walk from the right. Ignore trailing spaces, then count until the next space or the start.

The last word is the last run of non-space characters. Starting from the end means you never look at the earlier words.

Algorithm

  1. Skip trailing spaces.
  2. Count the next run of letters.
  3. Return the count.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def lengthOfLastWord(self, s: str) -> int:        i = len(s) - 1        while i >= 0 and s[i] == " ":            i -= 1        n = 0        while i >= 0 and s[i] != " ":            n += 1            i -= 1        return n
Watch this run

03

Interactive walkthrough

Playing “Skip trailing spaces, then count”. Edit the input, hit Run, then scrub.

Approach: Skip trailing spaces, then count

Loading animation…