LeetCode 58: Length of Last Word — Python Solution

LeetCode 58: Length of Last Word is an Easy array / string problem. This Python walkthrough develops a reverse scan solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

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

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, skip trailing spaces, then count characters until the next space or the beginning. The invariant worth writing beside the code is: Once trailing spaces are skipped, every counted character belongs to the final word.

Step-by-step algorithm

  1. Identify the input state consumed by lengthOfLastWord(s) and initialize the data required by the reverse scan pattern.
  2. Skip trailing spaces, then count characters until the next space or the beginning.
  3. After each update, verify the page’s central invariant: Once trailing spaces are skipped, every counted character belongs to the final word.
  4. Finish only after the boundary behavior is covered: There may be several trailing spaces or only one word.

Python solution

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

Reading the implementation

The main entry point is lengthOfLastWord(s). The named working state includes i, end; those variables make the reverse scan state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, skip trailing spaces, then count characters until the next space or the beginning.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Skip trailing spaces, then count characters until the next space or the beginning. Each update records the current item without invalidating earlier decisions; consequently, once trailing spaces are skipped, every counted character belongs to the final word.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

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

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().lengthOfLastWord("   fly me   to   the moon  ") == 4

Common mistakes and edge cases

  • Problem-specific boundary: There may be several trailing spaces or only one word.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that once trailing spaces are skipped, every counted character belongs to the final word.

Interview review checklist

  • Explain why reverse scan matches the structure of this input.
  • State the invariant in one sentence before tracing code: Once trailing spaces are skipped, every counted character belongs to the final word.
  • Derive O(n) worst-case time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: There may be several trailing spaces or only one word.

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