Length of Last Word
LeetCode 58 · Easy · solution, intuition & step-by-step walkthrough
Skip trailing spaces, count back to a space.
This is how I solved Length of Last Word (LeetCode 58), an easy problem from the Other pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Scan from the end: skip trailing spaces, then count characters until the next space or the start.
Approach
- 1
i at the last index; move left past spaces.
- 2
Count non-space characters moving left.
How I solved it
Reverse scanPythonO(n) time
class Solution:
def lengthOfLastWord(self, s: str) -> int:
#trime white space from right
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 lengthLength of Last Word — FAQ
What is the intuition behind Length of Last Word?
Scan from the end: skip trailing spaces, then count characters until the next space or the start.
How do you solve Length of Last Word (LeetCode 58)?
1. i at the last index; move left past spaces. 2. Count non-space characters moving left.
What is the time and space complexity of Length of Last Word?
Time: O(n). Space: O(1). (Accepted approach: Reverse scan.)
What are common mistakes in Length of Last Word?
Trailing spaces are the trap.