Length of Last Word - LEETCODE In 4K (Python)

preview_player
Показать описание
Length of Last Word LeetCode solutions. Explanation of different Python solutions to the common technical interview question: LeetCode #58 Length of Last Word.

In this video, I will explain 2 Length of Last Word LeetCode solutions using Python. I will also be explaining some unique Python language features along the way. Hope you enjoy!

Link to problem:

Problem Description:
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.

Timestamps:
0:00 Solution
2:06 One-line Solution (Pythonic)
2:23 Complexity Analysis

Find me on these platforms:

#python #coding #leetcode
Рекомендации по теме
Комментарии
Автор

Another Solution that uses only O(1) Space Complexity:


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


Instead of creating a list of all the words, we can simply iterate backwards until we hit a non-whitespace character. This means that we have hit the last character of the last word. We can then increment our length counter until we hit another whitespace (or index 0), which signals we have completed traversing the last word.

Time Complexity: O(N), N is the length of the string s
Space Complexity O(1)

PeterBohai