Skip to main content

58. Length of Last Word

easy

Return 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 Alex Chen, 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^4
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Examples

Example 1

Input
s = "Hello World"
Output
5

Explanation: The last word is "World" with length 5.

Example 2

Input
s = "   fly me   to   the moon  "
Output
4

Explanation: The last word is "moon" with length 4.

Example 3

Input
s = "luffy is still joyboy"
Output
6

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

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

Practice these live with InterviewChamp.AI

Drill Length of Last Word and Strings problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →