Length of Last Word
Length of Last Word is a easy arrays & hashing problem solved with the string basics pattern.
The best approach, optimal (scan back from the end), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (split into words) up.
Problem
You are given a string s made of English letters and space characters ' '.
A word is a maximal block of consecutive letters: it has no spaces inside it, and it cannot be extended to the left or to the right without hitting a space or an end of the string. The string may have spaces at the start, at the end, and several spaces between two words, but it always contains at least one word.
Return the number of letters in the last word of s.
Examples
Example 1
- Input
s = "Sorting is fun"- Output
3- Why
- The words are "Sorting", "is" and "fun". The last one, "fun", has 3 letters.
Example 2
- Input
s = " keep going "- Output
5- Why
- Spaces at the start, between the words and at the end do not matter. The last word is "going", with 5 letters.
Example 3
- Input
s = "z"- Output
1- Why
- The whole string is one word of length 1.
Constraints
1 <= s.length <= 10^4scontains only English letters (upper or lower case) and spaces' 'scontains at least one word
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 21 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (split into words) | O(n) | O(n) |
| One pass from the left | O(n) | O(1) |
| Optimal (scan back from the end) | O(n) | O(1) |
1Brute force (split into words)
O(n)Trimming and splitting each read the whole string once.O(n)The trimmed copy and the list of words together hold up to n characters.Cut the string into its words and measure the last one. Trimming the spaces at both ends first and then splitting on runs of one or more spaces gives exactly the list of words, with no empty pieces. The answer is the length of the last piece. It is short to write, but it builds every word of the string just to look at one.
- Remove the spaces at both ends of s.
- Split the rest on one or more spaces to get the words.
- Return the length of the last word.
class Solution {
public int lengthOfLastWord(String s) {
String[] words = s.trim().split(" +");
return words[words.length - 1].length();
}
}class Solution:
def lengthOfLastWord(self, s: str) -> int:
words = s.split()
return len(words[-1])class Solution {
public:
int lengthOfLastWord(string s) {
istringstream in(s);
string word, last;
while (in >> word) last = word;
return last.size();
}
};function lengthOfLastWord(s) {
const words = s.trim().split(/ +/);
return words[words.length - 1].length;
}2One pass from the left
O(n)One pass over the n characters with constant work each.O(1)Only the two counters.Scan the string once and keep two numbers. cur is the length of the run of letters that ends at the current character: a letter adds one to it and a space resets it to 0. last is the length of the most recent word seen so far: after every letter it is set to cur. Spaces never touch last, so trailing spaces cannot erase it, and at the end last is the length of the final word.
- Set cur = 0 and last = 0.
- For each character c of s: if c is a space, set cur = 0. Otherwise add one to cur and set last = cur.
- Return last.
class Solution {
public int lengthOfLastWord(String s) {
int cur = 0, last = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
cur = 0;
} else {
cur++;
last = cur;
}
}
return last;
}
}class Solution:
def lengthOfLastWord(self, s: str) -> int:
cur = last = 0
for c in s:
if c == ' ':
cur = 0
else:
cur += 1
last = cur
return lastclass Solution {
public:
int lengthOfLastWord(string s) {
int cur = 0, last = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (s[i] == ' ') {
cur = 0;
} else {
cur++;
last = cur;
}
}
return last;
}
};function lengthOfLastWord(s) {
let cur = 0, last = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === ' ') {
cur = 0;
} else {
cur++;
last = cur;
}
}
return last;
}3Optimal (scan back from the end)
O(n)In the worst case (one long word) every character is read once, but usually only the trailing spaces and the last word are visited.O(1)Only the pointer and the counter.Only the end of the string matters, so start there. Move a pointer i left past the trailing spaces; now s[i] is the last letter of the last word. Keep moving left and counting while the characters are letters. The count stops at the first space or when i falls off the front of the string, and that count is the answer. The characters before the last word are never read.
- Set i = s.length - 1. While s[i] is a space, move i left.
- Set len = 0. While i >= 0 and s[i] is not a space, add one to len and move i left.
- Return len.
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (s.charAt(i) == ' ') i--;
int len = 0;
while (i >= 0 && s.charAt(i) != ' ') {
len++;
i--;
}
return len;
}
}class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while s[i] == ' ':
i -= 1
length = 0
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return lengthclass Solution {
public:
int lengthOfLastWord(string s) {
int i = (int) s.size() - 1;
while (s[i] == ' ') i--;
int len = 0;
while (i >= 0 && s[i] != ' ') {
len++;
i--;
}
return len;
}
};function lengthOfLastWord(s) {
let i = s.length - 1;
while (s[i] === ' ') i--;
let len = 0;
while (i >= 0 && s[i] !== ' ') {
len++;
i--;
}
return len;
}Edge cases to test
- Trailing spaces after the last word: they must be skipped, not counted, and must not make the answer 0
- Leading spaces, or several spaces between words: a split on a single space produces empty pieces
- The string is a single word with no spaces at all: the answer is the whole length
- A single letter, alone or surrounded by spaces: the answer is 1
- The last word is the longest or the shortest word: only its own length matters
Hints
Hint 1
A word is a maximal run of letters. You only care about the last such run.
Hint 2
Walk from left to right and keep the length of the run you are in. A space ends the run, but the answer must survive spaces that come after the last word.
Hint 3
Or walk from the right end: skip the spaces at the end first, then count letters until the next space or the start of the string.
FAQ
What is the best time complexity for Length of Last Word?
Optimal (scan back from the end) runs in O(n) time and O(1) extra space. In the worst case (one long word) every character is read once, but usually only the trailing spaces and the last word are visited.
Which pattern does Length of Last Word use?
It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Longest Common Prefix, Minimum Changes To Make Alternating Binary String, Rotate String.
Is there a brute force solution for Length of Last Word?
Yes. Brute force (split into words) takes O(n) time and O(n) space. Cut the string into its words and measure the last one.
Which edge cases should I test for Length of Last Word?
Trailing spaces after the last word: they must be skipped, not counted, and must not make the answer 0; Leading spaces, or several spaces between words: a split on a single space produces empty pieces; The string is a single word with no spaces at all: the answer is the whole length; A single letter, alone or surrounded by spaces: the answer is 1; The last word is the longest or the shortest word: only its own length matters.