Length of the Last Word in a Sentence

Solve this Problem
Easy5–10 min
Topics
Companies
Practice:GFG ↗
Given a string s consisting of words separated by spaces (possibly with trailing spaces), return the length of the last word — a maximal substring of non-space characters. Splitting the whole string into words works, but it does more than the question asks: every earlier word gets extracted and thrown away, just to reach the last one. Scanning backward from the end skips straight past the trailing spaces to the last word and counts it directly, without ever building the words that came before it.

Test Case 1:

Input:s = "Hello World "
Output:5
Explanation:The last word is "World" — note the trailing spaces, which don't count as part of any word.

Test Case 2:

Input:s = " fly me to the moon "
Output:4
Explanation:Multiple spaces between words are just as harmless as a single space — the last word is "moon".

Test Case 3:

Input:s = "luffy is still joyboy"
Output:6
Explanation:No trailing spaces here — the last word is "joyboy".

Constraints

  • 1 ≤ s.length ≤ 10⁴
  • s consists of English letters and spaces ' '
  • There is at least one word in s
  • s may have trailing spaces
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public int lengthOfLastWord(String s) {
3 int i = s.length() - 1;
4 while (i >= 0 && s.charAt(i) == ' ') {
5 i--;
6 }
7 int length = 0;
8 while (i >= 0 && s.charAt(i) != ' ') {
9 length++;
10 i--;
11 }
12 return length;
13 }
14}
15
H
e
l
l
o
W
o
r
l
d
i
Variables
i12
INITIALIZE

Start i at the last index, 12.

Step 1 / 10

Approach & Solutions

Brute Force — Split Into Words

Brute

Trim the string and split it on spaces into an array holding every word. The last word is just the array's final element. Correct, but it builds and stores every word even though all but the last one get thrown away immediately.

TimeO(n)
SpaceO(n)
1class Solution { 2 public int lengthOfLastWord(String s) { 3 String[] words = s.trim().split(" +"); 4 String last = words[words.length - 1]; 5 return last.length(); 6 } 7}

Optimal — Backward Scan

Optimal

Walk backward from the end of the string. First skip any trailing spaces. Then count characters until the next space (or the very start of the string) — that count is the last word's length. No array of words ever needs to exist.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int lengthOfLastWord(String s) { 3 int i = s.length() - 1; 4 while (i >= 0 && s.charAt(i) == ' ') { 5 i--; 6 } 7 int length = 0; 8 while (i >= 0 && s.charAt(i) != ' ') { 9 length++; 10 i--; 11 } 12 return length; 13 } 14}

Related Problems