Length of last word

October 6, 2022

two-pointers

Problem URL: Length of last word

We will first start from the end and move the end pointer till we find a character. Then we take another pointer beginning from the end character and move towards the beginning of the string until we find an empty character. Then return the difference between the beginning and end pointer as result.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        end = len(s)-1
        while s[end] == ' ' and end >= 0:
            end -= 1

        beg = end
        while s[beg] != ' ' and beg >= 0:
            beg -= 1

        return end - beg

Time Complexity: O(n)
Space Complexity: O(1)