To solve "Length of Last Word", quickly trim trailing spaces and scan backward to identify the last word. Count consecutive non-space characters to obtain its length. This approach directly leverages string handling without extra data structures, ensuring efficiency for typical interview constraints.
Problem Statement
Given a string s containing words separated by spaces, return the length of the last word. A word is defined as a maximal substring of non-space characters.
You must handle strings with trailing spaces correctly. For example, " fly me to the moon " should return 4, because the last word is "moon" despite leading and trailing spaces.
Examples
Example 1
Input: s = "Hello World"
Output: 5
The last word is "World" with length 5.
Example 2
Input: s = " fly me to the moon "
Output: 4
The last word is "moon" with length 4.
Example 3
Input: s = "luffy is still joyboy"
Output: 6
The last word is "joyboy" with length 6.
Constraints
- 1 <= s.length <= 104
- s consists of only English letters and spaces ' '.
- There will be at least one word in s.
Solution Approach
Trim and Split Method
Remove leading and trailing spaces, split the string by spaces, and return the length of the last element. This method directly leverages string manipulation but may allocate extra memory for the array.
Backward Scan Without Splitting
Scan the string from the end, skipping trailing spaces, then count characters until a space or the beginning of the string. This approach is space-efficient and handles large strings without extra storage.
Optimized Index Tracking
Track the index of the last space while iterating from the end. Compute the length as the difference between string end and last space index. This reduces operations by avoiding full backward scans when unnecessary.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(n) in all approaches, where n is the length of the string, since each character is inspected at most once. Space complexity varies: O(n) for the split approach, O(1) for backward scanning or index tracking.
What Interviewers Usually Probe
- Expectations of handling trailing spaces correctly.
- Interest in string traversal without extra data structures.
- Observation of O(1) space solutions for interview optimization.
Common Pitfalls or Variants
Common pitfalls
- Failing to ignore trailing spaces, leading to off-by-one errors.
- Using split blindly, which may allocate unnecessary memory.
- Counting spaces instead of word characters, miscalculating length.
Follow-up variants
- Return the last word itself instead of its length.
- Compute the length of the first word or any k-th word in a string.
- Handle punctuation or non-letter characters as part of words.
How GhostInterview Helps
- Highlights the string-driven pattern for detecting the last word efficiently.
- Guides through backward scan techniques to avoid common off-by-one mistakes.
- Provides step-by-step reasoning for handling spaces and large strings in interviews.
Topic Pages
Related GhostInterview Pages
- LeetCode Interview Copilot - Use GhostInterview as a live solver when you want direct help with LeetCode-style coding questions.
- Coding Interview Assistant - See how GhostInterview supports array, string, linked list, graph, and tree interview workflows.
- How GhostInterview Works - Review the screenshot, reasoning, and answer flow before using the solver in a live interview.
FAQ
What is the most efficient approach for Length of Last Word?
A backward scan without splitting is most efficient, giving O(n) time and O(1) space by counting non-space characters from the end.
Do trailing spaces affect the result?
Yes, trailing spaces must be skipped; otherwise, the algorithm may return an incorrect length.
Can I use built-in split functions?
Yes, but splitting allocates extra memory and may be less efficient for very long strings.
How do I handle a string with a single word?
The last word is the entire string, so return its length after trimming any spaces.
Does the string-driven solution pattern generalize?
Yes, scanning and counting characters from the end is a common string-driven pattern applicable to other word-length or parsing problems.
Need direct help with Length of Last Word instead of spending more time grinding it?
Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Length of Last Word from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.
Capture the prompt fast instead of rewriting the problem by hand.
Get the solution path, trade-offs, and complexity summary in one pass.
Stay outside captured layers on supported screen-share workflows.
Stay in the same pattern family
Determine if a given string represents a valid number using precise string parsing and character validation rules.
Open problem page#49 Group AnagramsGroup the anagrams in a list of strings using efficient hash table-based methods, focusing on array scanning.
Open problem page#67 Add BinaryAdd Binary involves summing two binary strings and returning the result as a binary string using math and string manipulation.
Open problem page