Back to solutions

Length of Last Word

EasyArrays

Return the length of the final word in a string.

Constraints
  • 1 <= length <= 10^4
  • Letters and spaces only, at least one word

Scan from the right

Time O(n)Space O(1)

Start at the end of the string. Skip any trailing spaces, then count characters until you hit the next space or the start. That count is the length of the last word.

Key terms
trailing spaces:
Space characters after the last word that must be skipped first.
int lengthOfLastWord(const string& s) {
    int i = s.size() - 1, len = 0;
    while (i >= 0 && s[i] == ' ') i--;
    while (i >= 0 && s[i] != ' ') { len++; i--; }
    return len;
}
Step by step
  1. Move an index i from the last character leftwards while it points at a space.
  2. Now i is the last letter of the final word.
  3. Count letters while moving left until a space or the string start.
  4. Return that count.