easyStringArrays & Hashing

Length of Last Word

easyTime: O(n)Space: O(1)

Recognize the pattern

find last word in stringhandle trailing spacesstring traversal

Brute force idea

If you approach Length of Last Word in the most literal way possible, you get this: Split by spaces, return length of last element — but creates extra strings. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in Length of Last Word comes when you notice this: Scan from the end, skip trailing spaces, count characters. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Length of Last Word is this: Start from the end to find the last word without processing the entire string. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in Length of Last Word is this: Not handling trailing spaces — 'Hello World ' should return 5. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Arrays & Hashing Pattern