Skip to main content

Leetcode 58: Length of Last Word


1. Problem Statement (Simple Explanation)


You’re given a string s that contains:

  • English letters

  • Spaces ' '

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:

  1. Start from the last index and skip all trailing spaces.

  2. 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.


4. Java code


5. C code



6. C++ code




7. Python code




8. JavaScript code




Comments