Given a string s consisting of upper/lower-case alphabets and empty space characters ' ', return the length of the last word in the string. If the last word does not exist, return 0.
Examples:
Input : s = "Geeks For Geeks"
Output : 5
Explanation: length(Geeks)= 5Input : s = "Start Coding Here"
Output : 4
Explanation: length(Here) = 4Input : s= " "
Output : 0
Table of Content
[Naive Approach] Using String Splitting – O(n) Time and O(n) Space
The idea is to split the given string into separate words using spaces as delimiters. All extracted words are stored in a array, and the length of the last stored word is returned as the answer.
- Traverse the string character by character
- Build words until a space is encountered
- Store each word into a array
- After traversal, return the length of the last word in the array
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int lastWordLen(string &str) {
vector<string> lis;
string word = "";
for (char c : str) {
if (c == ' ') {
// Only push non-empty words
if (!word.empty()) {
lis.push_back(word);
word = "";
}
} else {
word += c;
}
}
// Don't automatically push - check if word is not empty
if (!word.empty()) {
lis.push_back(word);
}
return lis.empty() ? 0 : lis.back().length();
}
// Driver code
int main() {
string str = "Geeks for Geeks";
cout << "The length of last word is "
<< lastWordLen(str) << endl;
return 0;
}
// Java program to find length of last word
import java.util.*;
class GfG {
static int lastWordLen(String str) {
List<String> list = new ArrayList<>();
StringBuilder word = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
// Only push non-empty words
if (word.length() > 0) {
list.add(word.toString());
word = new StringBuilder();
}
} else {
word.append(c);
}
}
// Don't automatically push - check if word is not empty
if (word.length() > 0) {
list.add(word.toString());
}
return list.isEmpty() ? 0 : list.get(list.size() - 1).length();
}
// Driver code
public static void main(String[] args) {
String str = "Geeks for Geeks";
System.out.println("The length of last word is " + lastWordLen(str));
}
}
# Python program to find length of last word
def lastWordLen(s):
words = []
word = ""
for c in s:
if c == ' ':
# Only push non-empty words
if word:
words.append(word)
word = ""
else:
word += c
# Don't automatically push - check if word is not empty
if word:
words.append(word)
return len(words[-1]) if words else 0
# Driver code
if __name__ == "__main__":
s = "Geeks for Geeks"
print(f"The length of last word is {lastWordLen(s)}")
// C# program to find length of last word
using System;
using System.Collections.Generic;
class GfG {
static int lastWordLen(string str) {
List<string> list = new List<string>();
string word = "";
foreach (char c in str) {
if (c == ' ') {
// Only push non-empty words
if (word.Length > 0) {
list.Add(word);
word = "";
}
} else {
word += c;
}
}
// Don't automatically push - check if word is not empty
if (word.Length > 0) {
list.Add(word);
}
return list.Count == 0 ? 0 : list[list.Count - 1].Length;
}
// Driver code
static void Main(string[] args) {
string str = "Geeks for Geeks";
Console.WriteLine("The length of last word is " + lastWordLen(str));
}
}
// JavaScript program to find length of last word
function lastWordLen(str) {
let words = [];
let word = "";
for (let c of str) {
if (c === ' ') {
// Only push non-empty words
if (word.length > 0) {
words.push(word);
word = "";
}
} else {
word += c;
}
}
// Don't automatically push - check if word is not empty
if (word.length > 0) {
words.push(word);
}
return words.length === 0 ? 0 : words[words.length - 1].length;
}
// Driver code
const str = "Geeks for Geeks";
console.log(`The length of last word is ${lastWordLen(str)}`);
Output
The length of last word is 5
[Regex Approach] Using Regular Expression Matching – O(n) Time and O(n) Space
The idea is to use a regular expression to directly extract the last word from the string. The regex pattern searches for the sequence of non-space characters occurring at the end of the string. Once the last word is found, its length is returned.
- Define a regex pattern to match the last word in the string
- Use regex search to extract the matched substring
- Store the extracted last word
- Return the length of the matched word
#include <iostream>
#include <regex>
#include <algorithm>
using namespace std;
int lastWordLen(string &s) {
// First, trim trailing spaces
string trimmed = s;
trimmed.erase(trimmed.find_last_not_of(' ') + 1);
if (trimmed.empty()) return 0;
// Now find the last word (one or more non-space chars at the end)
regex re("[^ ]+$"); // Note: + instead of *
smatch match;
if (regex_search(trimmed, match, re)) {
return match.str().length();
}
return 0;
}
int main() {
string str = "Geeks for Geeks";
cout << "The length of last word is "
<< lastWordLen(str) << endl;
return 0;
}
// Java program to find length of last word using trimming and regex
import java.util.regex.*;
class GfG {
static int lastWordLen(String s) {
// First, trim trailing spaces
String trimmed = s.replaceAll("\\s+$", "");
if (trimmed.isEmpty()) return 0;
// Now find the last word (one or more non-space chars at the end)
Pattern pattern = Pattern.compile("[^ ]+$");
Matcher matcher = pattern.matcher(trimmed);
if (matcher.find()) {
return matcher.group().length();
}
return 0;
}
public static void main(String[] args) {
String s = "Geeks For Geeks";
System.out.println(lastWordLen(s));
}
}
# Python program to find length of last word using trimming and regex
import re
def lastWordLen(s):
# First, trim trailing spaces
trimmed = s.rstrip()
if not trimmed:
return 0
# Now find the last word (one or more non-space chars at the end)
match = re.search(r'[^ ]+$', trimmed)
return len(match.group()) if match else 0
# Driver code
if __name__ == "__main__":
s = "Geeks For Geeks"
print(lastWordLen(s))
// C# program to find length of last word using trimming and regex
using System;
using System.Text.RegularExpressions;
class GfG {
static int lastWordLen(string s) {
// First, trim trailing spaces
string trimmed = s.TrimEnd();
if (string.IsNullOrEmpty(trimmed)) return 0;
// Now find the last word (one or more non-space chars at the end)
Regex regex = new Regex("[^ ]+$");
Match match = regex.Match(trimmed);
return match.Success ? match.Value.Length : 0;
}
static void Main(string[] args) {
string s = "Geeks For Geeks";
Console.WriteLine(lastWordLen(s));
}
}
// JavaScript program to find length of last word using trimming and regex
function lastWordLen(s) {
// First, trim trailing spaces
let trimmed = s.trimEnd();
if (trimmed.length === 0) return 0;
// Now find the last word (one or more non-space chars at the end)
let match = trimmed.match(/[^ ]+$/);
return match ? match[0].length : 0;
}
// Driver code
const s = "Geeks For Geeks";
console.log(lastWordLen(s));
Output
The length of last word is 5
[Efficient Approach] Using String Traversal – O(n) Time and O(1) Space
The idea is to first remove leading and trailing spaces from the string. Then, traverse the string character by character while counting the length of the current word. Whenever a space is encountered, the counter is reset. At the end of traversal, the counter stores the length of the last word.
- Remove leading and trailing spaces from the string
- Traverse the string from left to right
- Increment count for non-space characters
- Reset count whenever a space appears
- Return the final count representing the last word length
// C++ program for the above approach
#include <iostream>
#include <string>
using namespace std;
int lastWordLen(string &s) {
int len = 0;
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ')
len = 0;
else
len++;
}
return len;
}
int main() {
string input = "Geeks For Geeks ";
cout << "The length of last word is "
<< lastWordLen(input) << endl;
return 0;
}
// C++ program for the above approach
import java.util.*;
class GFG {
static int lastWordLen(String s) {
int len = 0;
s = s.replaceAll("^\\s+", "");
s = s.replaceAll("\\s+$", "");
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ')
len = 0;
else
len++;
}
return len;
}
public static void main(String[] args) {
String input = "Geeks For Geeks ";
System.out.println("The length of last word is "
+ lastWordLen(input));
}
}
# C++ program for the above approach
def lastWordLen(s):
len1 = 0
s = s.lstrip()
s = s.rstrip()
for i in range(len(s)):
if s[i] == ' ':
len1 = 0
else:
len1 += 1
return len1
input_str = "Geeks For Geeks "
print("The length of last word is",
lastWordLen(input_str))
// C++ program for the above approach
using System;
class GFG {
static int lastWordLen(string s) {
int len = 0;
s = s.TrimStart();
s = s.TrimEnd();
for (int i = 0; i < s.Length; i++) {
if (s[i] == ' ')
len = 0;
else
len++;
}
return len;
}
static void Main() {
string input = "Geeks For Geeks ";
Console.WriteLine("The length of last word is "
+ lastWordLen(input));
}
}
// C++ program for the above approach
function lastWordLen(s) {
let len = 0;
s = s.trimStart();
s = s.trimEnd();
for (let i = 0; i < s.length; i++) {
if (s[i] === ' ')
len = 0;
else
len++;
}
return len;
}
let input = "Geeks For Geeks ";
console.log("The length of last word is "
+ lastWordLen(input));
Output
The length of last word is 5