Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for LeetCode Challenge: 58. Length of Last Word - JavaScript Solution🚀
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on

     

LeetCode Challenge: 58. Length of Last Word - JavaScript Solution🚀

Top Interview 150

String manipulation is a common coding interview topic, and this problem is a great example of working with substrings efficiently. Let’s solveLeetCode 58: Length of Last Word using a straightforward approach.


🚀 Problem Description

Given a strings consisting of words and spaces, return the length of the last word in the string.

  • A word is defined as a maximal substring consisting of non-space characters only.

💡 Examples

Example 1

Input:s="Hello World"Output:5Explanation:Thelastwordis"World"withlength5.
Enter fullscreen modeExit fullscreen mode

Example 2

Input:s="fly me to the moon"Output:4Explanation:Thelastwordis"moon"withlength4.
Enter fullscreen modeExit fullscreen mode

Example 3

Input:s="luffy is still joyboy"Output:6Explanation:Thelastwordis"joyboy"withlength6.
Enter fullscreen modeExit fullscreen mode

🏆 JavaScript Solution

The problem can be solved by trimming unnecessary spaces and locating the last word efficiently.

Implementation

varlengthOfLastWord=function(s){constwords=s.trim().split('');returnwords[words.length-1].length;};
Enter fullscreen modeExit fullscreen mode

🔍 How It Works

  1. Trim the String:
    • Remove leading and trailing spaces usingtrim() to simplify the logic.
  2. Split the String:
    • Usesplit(' ') to divide the string into words based on spaces.
  3. Get the Last Word:
    • Access the last element of the array (words[words.length - 1]) and return its length.

🔑 Complexity Analysis

  • > Time Complexity:O(n) is the length of the string. Trimming and splitting the string both run in linear time.
  • > Space Complexity:O(n), as splitting creates an array of words.

Alternative Solution (No Split)

For improved space efficiency, traverse the string backward to find the last word:

varlengthOfLastWord=function(s){letlength=0;leti=s.length-1;// Skip trailing spaceswhile(i>=0&&s[i]===''){i--;}// Count characters of the last wordwhile(i>=0&&s[i]!==''){length++;i--;}returnlength;};
Enter fullscreen modeExit fullscreen mode

🔑 Complexity Analysis (Alternative Solution)

  • > Time Complexity:O(n), as we traverse the string once.
  • > Space Complexity:O(1), as no extra data structures are used.

📋 Dry Run

Input:s = "fly me to the moon"
Length of Last Word
Output:4


✨ Pro Tips for Interviews

  1. Clarify constraints:

    • Can the string be empty?
    • Are there multiple spaces between words?
  2. Optimize for edge cases:

    • Input with only spaces (" "0).
    • Single-word input ("hello"5).

📚 Learn More

Check out the full explanation and code walkthrough on my Dev.to post:
👉Length of Last Word - JavaScript Solution

How would you solve this problem? Let’s discuss! 🚀

JavaScript #LeetCode #CodingInterview #ProblemSolving

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
rahulgithubweb profile image
Rahul Kumar Barnwal
Full-stack developer | Passionate about Problem Solving, Node.js, React, and Next.js | Tech mentor @ Polaris | Open Source Contributor | Sharing insights on coding, SaaS, and project building 🚀
  • Location
    Bangalore, Karnataka
  • Education
    B.Tech in Electronics and Communication Engineering | Vinoba Bhave University | Graduated Dec 2020
  • Pronouns
    He/Him
  • Work
    Senior Backend Developer | Tech Mentor @ Polaris | Open Source Contributor
  • Joined

Follow Me on GitHub 🚀

If you found this solution helpful, check out more of my projects and solutions on myGitHub profile.

Don't forget to follow for more updates!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-stack developer | Passionate about Problem Solving, Node.js, React, and Next.js | Tech mentor @ Polaris | Open Source Contributor | Sharing insights on coding, SaaS, and project building 🚀
  • Location
    Bangalore, Karnataka
  • Education
    B.Tech in Electronics and Communication Engineering | Vinoba Bhave University | Graduated Dec 2020
  • Pronouns
    He/Him
  • Work
    Senior Backend Developer | Tech Mentor @ Polaris | Open Source Contributor
  • Joined

More fromRahul Kumar Barnwal

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp