LeetCode 58: Length of Last Word — Python Solution

Solve LeetCode 58: Length of Last Word in Python with a reverse scan approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyEasy
TopicArray / String
Reusable patternreverse scan
ComplexityO(n) worst-case time and O(1) extra space

What the problem is testing

Skip trailing spaces, then count characters until the next space or the beginning.

Algorithm

  1. Skip trailing spaces, then count characters until the next space or the beginning.
  2. Maintain this invariant: Once trailing spaces are skipped, every counted character belongs to the final word.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def lengthOfLastWord(self, s):
        i = len(s) - 1
        while i >= 0 and s[i] == " ":
            i -= 1
        end = i
        while i >= 0 and s[i] != " ":
            i -= 1
        return end - i

Why this is correct

The proof follows the maintained state: Once trailing spaces are skipped, every counted character belongs to the final word. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) worst-case time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

There may be several trailing spaces or only one word.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 12. Integer to Roman · Next: 14. Longest Common Prefix