LeetCode 58: Length of Last Word Solution in Python Explained

Problem Statement

Section link icon

LeetCode 58, Length of Last Word, is an easy-level problem where you’re given a string s consisting of words and spaces. Your task is to return the length of the last word in the string. A word is defined as a maximal substring of non-space characters. The string may contain leading, trailing, or multiple consecutive spaces.

Constraints

  • 1 <= s.length <= 10^4: String length is between 1 and 10,000.
  • s consists of only English letters and spaces ' '.
  • There is at least one word in s.

Example

Input: s = "Hello World"
Output: 5
Explanation: Last word is "World", length 5.

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: Last word is "moon", length 4 (trailing spaces ignored).

Input: s = "luffy is still joyboy"
Output: 6
Explanation: Last word is "joyboy", length 6.

Understanding the Problem

Section link icon

How do you solve LeetCode 58: Length of Last Word in Python? For s = "Hello World", find the length of the last word "World", which is 5. The string may have extra spaces, so we need to identify the final sequence of non-space characters. We’ll explore two approaches: an Iterative Reverse Scan Solution (optimal and primary) and an Alternative with Split (intuitive but less efficient). The reverse scan method runs in O(n) time with O(1) space by scanning from the end.

Solution 1: Iterative Reverse Scan Approach (Primary)

Section link icon

Explanation

Scan the string from the end to the start, skipping trailing spaces until the last word is found, then count its characters until a space or the start is reached. This avoids processing the entire string unnecessarily and uses constant space.

Here’s a flow for " fly me to the moon ":

End: Skip spaces -> "moon  "
Count: "moon" -> 4 characters
Stop at space, return 4
  1. Start from End.
  • Begin at the last character.
  1. Skip Trailing Spaces.
  • Move left until a non-space is found.
  1. Count Last Word.
  • Count characters until a space or start.
  1. Return Length.

Step-by-Step Example

Example 1: s = "Hello World"

We need 5.

  • Goal: Find length of last word.
  • Result for Reference: 5.
  • Start: s = "Hello World", i = 10 (last index).
  • Step 1: i = 10, s[10] = 'd'.
    • Non-space, start counting.
  • Step 2: Count "World".
    • i = 10, 'd', length = 1.
    • i = 9, 'l', length = 2.
    • i = 8, 'r', length = 3.
    • i = 7, 'o', length = 4.
    • i = 6, 'W', length = 5.
    • i = 5, ' ', stop.
  • Finish: Return 5.

Example 2: s = " fly me to the moon "

We need 4.

  • Start: i = 25 (last index).
  • Step 1: Skip trailing spaces.
    • i = 25, ' ', i = 24, ' ', i = 23, ' ', i = 22, 'n'.
  • Step 2: Count "moon".
    • i = 22, 'n', length = 1.
    • i = 21, 'o', length = 2.
    • i = 20, 'o', length = 3.
    • i = 19, 'm', length = 4.
    • i = 18, ' ', stop.
  • Finish: Return 4.

How the Code Works (Iterative Reverse Scan)

Here’s the Python code with line-by-line explanation:

def lengthOfLastWord(s: str) -> int:
    # Line 1: Initialize index and length
    i = len(s) - 1
    length = 0

    # Line 2: Skip trailing spaces
    while i >= 0 and s[i] == ' ':
        i -= 1

    # Line 3: Count last word
    while i >= 0 and s[i] != ' ':
        length += 1
        i -= 1

    # Line 4: Return length
    return length

Alternative: Split Approach

Section link icon

Explanation

Split the string into words using spaces as delimiters, then take the length of the last non-empty word. This is simpler but less efficient due to string splitting and potential extra memory usage.

  1. Split String.
  • Convert to list of words.
  1. Get Last Word.
  • Access the final element.
  1. Return Length.

Step-by-Step Example (Alternative)

For " fly me to the moon ":

  • Start: s = " fly me to the moon ".
  • Step 1: Split.
    • words = ['', '', '', 'fly', 'me', '', '', 'to', '', '', 'the', 'moon', '', ''].
  • Step 2: Filter non-empty (optional) or take last non-empty.
    • Last word = "moon".
  • Step 3: Length of "moon" = 4.
  • Finish: Return 4.

How the Code Works (Split)

def lengthOfLastWordSplit(s: str) -> int:
    # Line 1: Split string into words
    words = s.split()

    # Line 2: Return length of last word
    return len(words[-1])

Complexity

  • Iterative Reverse Scan:
    • Time: O(n) – Single pass from end, where n is string length.
    • Space: O(1) – Only two variables.
  • Split Approach:
    • Time: O(n) – Splitting processes entire string.
    • Space: O(n) – Stores list of words.

Efficiency Notes

Iterative Reverse Scan is O(n) time and O(1) space, optimal for LeetCode 58 as it avoids unnecessary memory allocation. Split is also O(n) time but uses O(n) space for the word list, less efficient but more concise.

Key Insights

Tips to master LeetCode 58:

  • Reverse Thinking: Start from end to find last word fast.
  • Space Handling: Skip trailing spaces explicitly.
  • Minimal Memory: Avoid splitting for efficiency.

Additional Example

Section link icon

For s = "luffy is still joyboy":

  • Goal: 6.
  • Reverse Scan: "joyboy" -> 6.
  • Result: 6.

Edge Cases

Section link icon
  • Single Word: "hello" – Return 5.
  • All Spaces: " " – Return 0 (but constraint ensures a word).
  • Leading Spaces: " hi" – Return 2.

Final Thoughts

Section link icon

The Iterative Reverse Scan solution is a sleek choice for LeetCode 58 in Python—fast, space-efficient, and straightforward. For a related challenge, try LeetCode 57: Insert Interval to switch gears with intervals! Ready to measure words? Solve LeetCode 58 on LeetCode now and test it with "Hello World" or " fly me to the moon " to nail your string skills. Dive in and count it up!