Length of Last Word — LeetCode 58 Python Solution

EasyString
Problem
#58
Pattern
Hash Map
Reading time
2 min

The problem

Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.

Example

Input
s = "Hello World"
Output
5
Explanation
The last word is "World" with length 5.

Python solution

Python
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i = len(s) - 1
        while i >= 0 and s[i] == ' ':
            i -= 1
        j = i
        while j >= 0 and s[j] != ' ':
            j -= 1
        return i - j

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 58. Length of Last Word is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 58. Length of Last Word?
LeetCode 58. Length of Last Word is rated Easy on LeetCode.
What is the time complexity of LeetCode 58. Length of Last Word?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 58. Length of Last Word?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 58. Length of Last Word cover?
LeetCode 58. Length of Last Word is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview