58. Length of Last Word
easyReturn the length of the last word in a string that may contain trailing spaces. A short problem that punishes anyone who reaches for split() on a 10^4-character input.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.
Constraints
1 <= s.length <= 10^4s consists of only English letters and spaces ' '.There will be at least one word in s.
Examples
Example 1
s = "Hello World"5Explanation: The last word is "World" with length 5.
Example 2
s = " fly me to the moon "4Explanation: The last word is "moon" with length 4.
Example 3
s = "luffy is still joyboy"6Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
split() works but allocates O(n) extra strings just to throw most of them away.
Hint 2
Walk the string from the end. Skip past trailing spaces first.
Hint 3
Once you hit a non-space, count how many non-space characters you see before the next space or the start of the string.
Solution approach
Reveal approach
Reverse linear scan, two phases. Start i at s.length-1. Phase one: while i >= 0 and s[i] is a space, decrement i — this swallows trailing spaces. Phase two: initialise length = 0, then while i >= 0 and s[i] is not a space, increment length and decrement i. Return length. O(n) worst-case time but typically far less, O(1) extra space.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- two-pointers
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
More Strings practice problems
- 3. Longest Substring Without Repeating Characters
- 5. Longest Palindromic Substring
- 6. Zigzag Conversion
- 14. Longest Common Prefix
- 20. Valid Parentheses
- 28. Find the Index of the First Occurrence in a String
- 49. Group Anagrams
- 76. Minimum Window Substring