const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Length of Last Word: LeetCode 58 Solution Explained

LeetCode 58 is one of the simplest string problems, but it teaches reverse iteration and trailing space handling — two skills that pay off in harder problems.

5 min read|

Two while loops, zero extra space, one clean solution

LeetCode 58 — the simplest string problem that teaches reverse iteration

Length of Last Word: Why This Easy Problem Matters

Length of Last Word (#58) is one of the first string problems most people encounter on LeetCode. The task is deceptively simple: given a string of words separated by spaces, return the length of the last word. But the twist that catches beginners off guard is trailing spaces.

This length of last word leetcode problem is a perfect warm-up because it introduces two fundamental string processing skills: handling whitespace edge cases and iterating in reverse. Both techniques appear in dozens of harder problems, making #58 a foundational building block for your string pattern toolkit.

In this walkthrough, we will cover two approaches — a quick split-based solution and an optimal reverse iteration approach — so you understand both the convenient way and the efficient way to solve it.

Understanding the Length of Last Word Problem

The problem gives you a string s consisting of words and spaces. A word is a maximal substring of non-space characters. You need to return the length of the last word in the string.

The key constraint that makes this interesting is that s may have trailing spaces. For example, "Hello World " still has "World" as the last word with length 5, even though the string ends with spaces. The string is guaranteed to have at least one word.

This is where many first attempts fail — if you simply split and grab the last element, trailing spaces can produce empty strings in your array. Understanding this edge case is exactly what the leetcode 58 solution tests.

ℹ️

Good to Know

Length of Last Word (#58) is one of the easiest Easy problems — it's a good warm-up that tests whether you handle trailing spaces correctly.

Approach 1: Trim and Split

The most intuitive approach is to strip trailing spaces, split the string by spaces, and return the length of the last element. In most languages, this is a one-liner. In Python: return len(s.strip().split()[-1]). In JavaScript: return s.trim().split(" ").pop().length.

This trim and split approach works correctly and is easy to read. You first remove trailing (and leading) whitespace, then split on spaces to get an array of words, and finally check the length of the last word in the array.

The downside is that split creates an entire array of all words in the string. If the string has n characters and w words, you are allocating O(w) extra space for an array you only need the last element of. For a short string this is negligible, but it is worth knowing the trade-off.

Approach 2: Reverse Iterate (Optimal)

The optimal approach for this length of last word leetcode problem uses reverse iteration. Start from the end of the string and work backwards in two phases: first skip any trailing spaces, then count characters until you hit a space or reach the beginning of the string.

The algorithm uses two simple while loops. The first loop decrements your index while the character at that position is a space — this handles trailing whitespace. The second loop counts non-space characters, incrementing a counter for each letter until you encounter a space or exhaust the string.

This reverse iterate string technique runs in O(n) time in the worst case (if the entire string is one word), but in practice it only touches the trailing spaces plus the last word. It uses O(1) extra space since you only need an index and a counter. No array allocation, no string copying.

💡

Pro Tip

Reverse iterate: skip spaces from the end, then count non-space characters. Two simple while loops, O(n) time, O(1) space. No split needed.

Visual Walkthrough: Length Last Word Explained

Let us trace through two examples to see the reverse iteration approach in action. For the input "Hello World", we start at index 10 (the "d" in "World"). No trailing spaces to skip, so we go straight to counting: d-l-r-o-W gives us 5. We hit a space at index 5 and return 5.

For a trickier input like " fly me to the moon ", we start at the end (index 27). The first while loop skips the two trailing spaces, landing on "n" at index 25. The second while loop counts: n-o-o-m gives us 4. We hit a space at index 21 and return 4. The leading spaces and intermediate spaces are never even visited.

This is the beauty of reverse iteration for last word string problems — you only touch the characters that matter. The entire prefix of the string is irrelevant, which makes this approach particularly efficient for strings with a short last word but a long overall length.

Edge Cases to Watch For

Even on an easy problem like leetcode 58 solution, covering edge cases shows thoroughness. The first edge case is a single word with no spaces, like "Hello". Both approaches handle this correctly — split returns a one-element array, and reverse iterate counts all characters.

Trailing spaces like "Hello World " are the classic trap. The split approach handles this if you trim first; the reverse iterate approach handles it naturally by skipping trailing spaces in the first loop. Leading spaces like " Hello" are not an issue for either approach since we only care about the last word.

A single character input like "a" should return 1. A string with many spaces between words like "a b" should return 1 (the length of "b"). Both approaches handle these correctly without special-casing.

  • Single word, no spaces: "Hello" -> 5
  • Trailing spaces: "Hello World " -> 5
  • Leading spaces: " Hello" -> 5
  • Single character: "a" -> 1
  • Multiple spaces between words: "a b" -> 1
⚠️

Space Trade-off

The split approach creates an O(n) array — while it works, the reverse iteration approach is O(1) space and shows the interviewer you think about efficiency even on Easy problems.

What Length of Last Word Teaches You

Length of Last Word is a gateway problem that introduces string processing easy patterns you will use everywhere. The reverse iteration technique — scanning from the end of a string instead of the beginning — appears in problems like Valid Palindrome, Reverse Words in a String, and Longest Common Suffix.

Trailing space handling is another transferable skill. Many string problems involve cleaning or normalizing input before processing it. Recognizing that you need to account for extra whitespace before diving into your main logic is a habit that prevents bugs in medium and hard problems.

If you are building your string pattern toolkit, Length of Last Word is a great starting point. From here, try Valid Palindrome (#125) for two-pointer string traversal, Longest Common Prefix (#14) for comparing multiple strings, and Reverse Words in a String (#151) for more advanced space handling. YeetCode flashcards can help you drill these string processing patterns until they become second nature.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now