The "Length of Last Word interview question" is a fundamental string processing challenge. Given a string s consisting of words and spaces, you need to return the length of the last word in the string. A word is defined as a maximal substring consisting of non-space characters only. This "Length of Last Word coding problem" tests your ability to handle whitespace and traverse strings from different directions.
This problem is a favorite for entry-level positions and screening rounds at companies like Apple and Microsoft. It evaluates basic string manipulation skills and the ability to handle edge cases like trailing spaces, multiple spaces between words, or strings containing only one word. It's an excellent way to see if a candidate can write concise, efficient code for a seemingly simple task.
The most efficient approach is a "String interview pattern" involving backward traversal. Instead of splitting the entire string into an array (which uses extra memory), you start from the end of the string. First, skip any trailing spaces. Then, count the characters until you encounter another space or reach the beginning of the string. This O(n) time and O(1) space solution is highly optimized.
String: "Hello World "
split() or trim() in languages where these operations create new strings, leading to O(n) space complexity when O(1) is possible.Always consider traversing strings from right to left if the problem asks about the "last" element. This often simplifies the logic and reduces the need for extra data structures.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Original Typed String I | Easy | Solve | |
| Valid Word | Easy | Solve | |
| Detect Capital | Easy | Solve | |
| Score of a String | Easy | Solve | |
| Delete Characters to Make Fancy String | Easy | Solve |