Magicsheet logo

Length of Last Word

Easy
42.9%
Updated 6/1/2025

Length of Last Word

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

String: "Hello World "

  1. Trailing spaces: Start from the end. Ignore the spaces at the very end.
  2. Start counting: We encounter 'd', 'l', 'r', 'o', 'W'. Count = 5.
  3. End word: We encounter a space before "World". Stop counting. The length of the last word "World" is 5.

Common mistakes candidates make

  • Not handling trailing spaces: Starting the count immediately from the last index, which might be a space.
  • Memory inefficiency: Using split() or trim() in languages where these operations create new strings, leading to O(n) space complexity when O(1) is possible.
  • Empty string case: Not properly returning 0 for strings that are empty or consist only of spaces.

Interview preparation tip

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.

Similar Questions