The “Length of Last Word“ problem is a classic problem often asked in coding interviews. The task is to determine the length of the last word in a given string. A word is defined as a sequence of non-space characters, and the words in the string are separated by spaces.
Problem Statement:
Given a string s
, return the length of the last word in it.
- A word is defined as a maximal substring of non-space characters.
- The string may contain leading or trailing spaces, so they should be ignored.
Example:
Input:
"Hello World"
Output:
5
Explanation: The last word is “World”, and its length is 5.
Input:
arduinoCopy code" fly me to the moon "
Output:
4
Explanation: The last word is “moon”, and its length is 4.
Input:
"luffy is still joyboy"
Output:
6
Explanation: The last word is “joyboy”, and its length is 6.
Approach:
We can solve this problem in two main ways:
- Iterate from the end of the string: Start from the end of the string and move backward. Skip spaces until you find the first non-space character. Once you find a character, count the length of the word until you encounter a space or the beginning of the string.
- Trim and split the string: Trim any leading or trailing spaces, then split the string by spaces and take the length of the last word in the resulting array of words.
Solution Approach 1: Iteration from the end
- Skip any trailing spaces.
- Count characters of the last word: Start from the last character of the string and move backward, counting characters until you encounter a space or the start of the string.
Solution Approach 2: Using built-in functions (trim, split)
- Trim the string: Remove any leading and trailing spaces.
- Split the string by spaces: This gives us all the words.
- Return the length of the last word.
Code Implementations:
1. C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int lengthOfLastWord(string s) {
int n = s.length();
int length = 0;
// Start from the end of the string
int i = n - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count the length of the last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
int main() {
string str = "Hello World";
cout << "Length of last word: " << lengthOfLastWord(str) << endl; // Output: 5
return 0;
}
2. C
#include <stdio.h>
#include <string.h>
int lengthOfLastWord(char *s) {
int len = strlen(s);
int length = 0;
// Skip trailing spaces
while (len > 0 && s[len - 1] == ' ') {
len--;
}
// Count the length of the last word
while (len > 0 && s[len - 1] != ' ') {
length++;
len--;
}
return length;
}
int main() {
char str[] = "Hello World";
printf("Length of last word: %d\n", lengthOfLastWord(str)); // Output: 5
return 0;
}
3. Java
public class LengthOfLastWord {
public int lengthOfLastWord(String s) {
int length = 0;
int n = s.length();
// Skip trailing spaces
int i = n - 1;
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
// Count the length of the last word
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
public static void main(String[] args) {
LengthOfLastWord solution = new LengthOfLastWord();
String str = "Hello World";
System.out.println("Length of last word: " + solution.lengthOfLastWord(str)); // Output: 5
}
}
4. Python
def lengthOfLastWord(s: str) -> int:
s = s.strip() # Remove leading/trailing spaces
words = s.split() # Split the string into words
return len(words[-1]) # Return the length of the last word
# Test the function
print(lengthOfLastWord("Hello World")) # Output: 5
5. C#
using System;
public class Solution {
public int LengthOfLastWord(string s) {
s = s.Trim(); // Remove leading/trailing spaces
string[] words = s.Split(); // Split the string into words
return words[words.Length - 1].Length; // Return the length of the last word
}
public static void Main() {
Solution solution = new Solution();
string str = "Hello World";
Console.WriteLine(solution.LengthOfLastWord(str)); // Output: 5
}
}
6. JavaScript
function lengthOfLastWord(s) {
s = s.trim(); // Remove leading/trailing spaces
const words = s.split(' '); // Split the string into words
return words[words.length - 1].length; // Return the length of the last word
}
// Test the function
console.log(lengthOfLastWord("Hello World")); // Output: 5
Time Complexity:
- Approach 1 (Iteration from the end):
The algorithm goes through the string once. The time complexity is O(n), where n is the length of the string. - Approach 2 (Trim and Split):
- Trimming: Takes O(n) time.
- Splitting: Splitting takes O(n) time, where n is the length of the string, as each character must be processed to split the string.
- The overall time complexity is O(n).
Space Complexity:
- Approach 1: Constant space O(1), since we only use a few extra variables.
- Approach 2: O(n) space due to the split operation, which creates a list of words.
Summary:
The “Length of Last Word” problem can be solved using either an iterative approach from the end of the string or by trimming and splitting the string. Both approaches have a time complexity of O(n), but the iterative approach can be more space-efficient, using O(1) extra space.