Length of Last Word

Easy · rating 850 · strings

Read a line of words separated by single or multiple spaces. Print the length of the last word.

Editorial

Length of Last Word is a simple string-parsing interview question: return the length of the final word in a string that may have trailing spaces and multiple separators.

Approach

Scan from the end: skip any trailing spaces, then count characters until you hit the next space or the start of the string. Walking backwards avoids splitting the whole string.

i = len(s) - 1
while i >= 0 and s[i] == ' ': i -= 1
length = 0
while i >= 0 and s[i] != ' ':
    length += 1; i -= 1
return length

Complexity

Time: O(n). Space: O(1).

Open Length of Last Word in Code Arena →