VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-last-word-in-a-string/

⇱ Length Of Last Word in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length Of Last Word in a String

Last Updated : 28 May, 2026

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)= 5

Input : s = "Start Coding Here"
Output : 4
Explanation: length(Here) = 4

Input : s= " "
Output : 0

[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

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

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

Output
The length of last word is 5
Comment
Article Tags: