Advertisement

Length of Last Word - LeetCode 58 Solution

Length of Last Word - Complete Solution Guide

Length of Last Word is LeetCode problem 58, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Example 2: Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4. Example 3: Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6. Constraints: 1

Detailed Explanation

This problem asks us to pinpoint the length of the *final* word in a given string `s`. Sounds simple enough, right? But the devil, as always, is in the details – specifically, how we define a 'word' and what constitutes 'last'. A word here isn't just any sequence of non-space characters; it's a *maximal* substring of non-space characters. This means 'Hello World' has 'Hello' and 'World' as words, not 'Hel' and 'lo'. The real challenge and the source of potential pitfalls lie in the diverse ways spaces can appear. Consider strings like `s = " fly me to the moon "`. We have leading spaces, trailing spaces, and multiple spaces between words. All these need to be handled gracefully so that 'moon' is correctly identified as the last word, and its length (4) is returned. The problem essentially boils down to intelligently parsing the string, dismissing superfluous whitespace, and isolating that very last meaningful sequence of characters.

Solution Approach

The provided Pythonic solution beautifully leverages built-in string methods to tackle this problem with remarkable conciseness and efficiency. Its elegance stems from a three-step dance. First, `s.strip()` is called. This essential step lops off any leading or trailing whitespace characters from the original string. This isn't just a nicety; it ensures that when we later split the string, we don't end up with empty strings at the beginning or end of our word list, which could confuse the 'last word' identification. For example, `" hello world "` becomes `"hello world"`. Next, `s.split()` takes center stage. When called without any arguments, Python's `split()` method is incredibly smart: it automatically splits the string by *any* sequence of whitespace characters (spaces, tabs, newlines) and, crucially, discards any resulting empty strings. This perfectly aligns with our 'maximal substring' definition of a word and cleanly separates words even when there are multiple spaces between them, like `"fly me to the moon"` turning into `['fly', 'me', 'to', 'moon']`. Finally, `words[-1]` directly accesses the very last element of the list of words. Python's negative indexing makes this trivial. Applying `len()` to this last word then gives us its character count, fulfilling the problem's requirement.

Step-by-Step Algorithm

  1. Step 1: Remove leading and trailing spaces from the input string (optional but recommended for clarity).
  2. Step 2: Locate the last word. This can be done by iterating from the end of the string (C++, efficient), using string splitting (Python), or finding the last space character's index (Java).
  3. Step 3: Calculate the length of the last word by counting characters from the end of the string until a space is found (or end of string is reached).
  4. Step 4: Return the calculated length.

Key Insights

  • **Strategic `str.strip()` usage:** Pre-processing the string with `s.strip()` is paramount. It intelligently removes all leading and trailing whitespace, ensuring that `split()` operates on a clean string and doesn't produce spurious empty strings at the list boundaries, which could otherwise throw off the identification of the 'last' word.
  • **`str.split()`'s default magic:** Leveraging `s.split()` without specifying a delimiter is a powerful Pythonic idiom. It's designed to split by *any* amount of whitespace and automatically handles multiple spaces between words by treating them as a single separator, while also discarding any empty strings that would otherwise result. This directly maps to the 'maximal substring' word definition.
  • **Python's Negative Indexing for 'Last':** Directly accessing the last element of the word list using `words[-1]` is an idiomatic and highly readable way to pinpoint the 'last word' in Python. It's clean, concise, and avoids needing to calculate the list's length and then subtract one for the index.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: String.

Companies

Asked at: Adobe, Amazon, Apple, Bloomberg, Meta, Microsoft, Qualcomm, Uber, Yahoo, tcs.