LeetCode 58. Length of Last Word | String Manipulation Solution in JavaScript

ShanksShanks
2 min read

📌 Introduction

In this post, we’ll solve LeetCode 58. Length of Last Word. We’ll cover a string manipulation approach, and analyze the time and space complexities. Code examples will be in JavaScript, with step-by-step explanations.

👉 Original problem link: LeetCode – Length of Last Word


1. Problem Overview

The problem asks us to find the length of the last word in a given string

s. The string consists of words and spaces. A "word" is defined as a sequence of non-space characters. The string is guaranteed to contain at least one word.


2. Example

Input: s = " fly me to the moon " Output: 4 Explanation: The string contains multiple words and spaces. After trimming, the last word is "moon", which has a length of 4.


3. Approaches

🔹 Optimized Approach

  • Idea:

    • First, remove any leading or trailing spaces from the string.

    • Next, split the string into an array of words using a regular expression that handles one or more spaces as a delimiter.

    • The last word will be the final element of the resulting array.

    • Return the length of that last word.

Code (JavaScript):

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    s = s.trim().split(/\s+/)
    return s[s.length - 1].length
};

Time Complexity = O(N) Space Complexity = O(N) - A new array is created which, in the worst-case scenario, stores all the characters of the original string.


4. Key Takeaways

  • ✨ String manipulation methods like trim() and split() can provide a concise solution for problems involving string parsing.

  • ✨ Regular expressions like /\s+/ are useful for handling varying amounts of whitespace between words.

  • ✨ For this specific problem, both split(' ') and split(/\s+/) work after trimming the string. The latter is more robust for cases with multiple spaces between words, though trimming makes both effective for the last word.

  • ✨ Regex note: when using the RegExp constructor, the backslash must be escaped,
    e.g., new RegExp('\\s+').

0
Subscribe to my newsletter

Read articles from Shanks directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shanks
Shanks

Senior Dev trying to crack FAANG | Sharing the grind, growth, and late-night code sessions