Practice › Strings
Length of the Last Word
Easy · Strings · Asked at Amazon, Google, TCS, Infosys, Wipro
The line contains words made of letters, separated by one or more spaces; there may be spaces at the start or the end. Print the length of the last word.
Input
A single line of text (letters and spaces, at least one word).
Output
The length of the last word.
Constraints
- 1 ≤ length ≤ 10^4
Scan from the end: skip trailing spaces, then count letters until the next space or the start of the line.
Example 1
Input
Hello World
Output
5
Example 2
Input
fly me to the moon
Output
4
Hints
- Read the whole line — it contains spaces.
- Trailing spaces do not belong to any word.
- Scan backwards: skip spaces, then count letters.
Approach
Start at the end of the line. Skip spaces (and a stray ' '), then count characters until you meet a space or the start of the line. That count is the length of the last word. No splitting or extra memory is needed.
Complexity: O(length) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin, s);
int i = (int) s.size() - 1;
while (i >= 0 && (s[i] == ' ' || s[i] == '\r')) i--;
int len = 0;
while (i >= 0 && s[i] != ' ') {
len++;
i--;
}
cout << len << "\n";
return 0;
}Python solution
import sys
s = sys.stdin.readline().rstrip("\r\n")
print(len(s.split()[-1]))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') i--;
int len = 0;
while (i >= 0 && s.charAt(i) != ' ') {
len++;
i--;
}
System.out.println(len);
}
}Solve Length of the Last Word online · All practice problems