File: length-of-last-word/solution.py

Date: 2026-06-06

Time: 17:22

length-of-last-word/solution.py

Purpose

This file implements the solution to LeetCode #58 — Length of Last Word. It owns exactly one responsibility: given a string of words separated by spaces, return the length of the last word. The function lengthoflast_word is the public API consumed by the test harness.

Key Components

lengthoflast_word(s: str) -> int — The sole function. Its contract:

Patterns

The implementation chains three built-in string/list operations in a single expression:

1. s.rstrip() — strips trailing spaces so a string like "hello world " becomes "hello world". This is the key defensive step; without it, split()[-1] would still work (since str.split() with no args already handles trailing whitespace), making the rstrip() technically redundant here but explicit about intent.

2. .split() — splits on any whitespace into a list of words. Using the no-arg form means consecutive spaces are collapsed and leading/trailing whitespace is ignored.

3. [-1] — grabs the last element.

4. len(...) — returns its length.

This is the idiomatic Python one-liner approach — no loops, no manual index tracking.

Dependencies

Imports: None. Pure stdlib, no external packages.

Imported by: The "Imported By" list in the prompt is misleading — those are test files for *other* problems, not actual consumers of this function. The real consumer is length-of-last-word/testsolution.py, which imports lengthoflastword to run test cases against it. The long list likely reflects a shared test runner or test infrastructure pattern across the repo rather than direct imports of this function.

Flow


input: "   fly me   to   the moon  "
       │
       ▼ rstrip()
"   fly me   to   the moon"
       │
       ▼ split()
["fly", "me", "to", "the", "moon"]
       │
       ▼ [-1]
"moon"
       │
       ▼ len()
4

Invariants

Error Handling

None. If s is empty or all-spaces, split() returns [] and [-1] raises IndexError. This is acceptable because the problem constraints guarantee at least one word exists. The function trusts its caller to meet the precondition.