← Back to Leo Academy Masterclass

Problem #58: Length of Last Word

Easy Array & String

Intuition & Strategy Breakdown

Trim trailing whitespace, then scan from right to left to count characters of the last word until encountering a space or start of string.

Python Solution

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

Java Solution

class Solution {
    public int lengthOfLastWord(String s) {
        int i = s.length() - 1, length = 0;
        while (i >= 0 && s.charAt(i) == ' ') i--;
        while (i >= 0 && s.charAt(i) != ' ') {
            length++;
            i--;
        }
        return length;
    }
}
Watch Interactive Video on Leo Academy Main App