1. Problem Statement (Simple Explanation)
You’re given a string s that contains:
English letters
Spaces ' '
A word is defined as a maximal substring of non-space characters.
You must return the length of the last word in s.
There is guaranteed to be at least one word in the string.
2. Examples
Example 1:
Input: s = "Hello World"
Last word = "World" → length = 5.
Output: 5
Example 2:
Input: s = " fly me to the moon "
Last word = "moon" → length = 4.
Output: 4
Example 3:
Input: s = "luffy is still joyboy"
Last word = "joyboy" → length = 6.
Output: 6
3. Approach – Scan from the End (O(n), O(1))
We only need the last word, so we can efficiently scan from the end of the string:
Start from the last index and skip all trailing spaces.
Then, count characters until:
We hit a space, or
We reach the beginning of the string.
That count is the length of the last word.
Pseudo-code:

Complexity:
Let n = len(s):
Time: O(n) in worst case (single pass from end).
Space: O(1) extra.


6. C++ code

7. Python code

8. JavaScript code

Comments
Post a Comment