Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

View on GitHub

Intuition

To find the length of the last word in a string, we can scan the string from the end, skipping any trailing spaces, and then count the characters until we hit another space or the start of the string.

Approach

Complexity

Code

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        n = len(s)

        ans = 0
        first_char = None
        for i in range(n - 1, -1, -1):
            c = s[i]
            if c == " " and first_char is not None:
                break
            elif c != " ":
                ans += 1
                first_char = first_char or c

        return ans

Back to Problem Statement