Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Length of Last Word

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "58" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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 <= s.length <= 104 s consists of only English letters and spaces ' '. There will be at least one word in s.

Explanation

Here's an efficient solution to find the length of the last word in a string, along with explanations:

  • Traverse from Right to Left: The most efficient way is to start from the end of the string and move backward.
  • Skip Trailing Spaces: First, skip any trailing spaces.
  • Count Characters: Once a non-space character is encountered, start counting until another space is found or the beginning of the string is reached.

  • Time Complexity: O(n), where n is the length of the string.

  • Space Complexity: O(1)

Code

    def lengthOfLastWord(s: str) -> int:
    """
    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.
    """
    s = s.rstrip()  # Remove trailing spaces
    length = 0
    for i in range(len(s) - 1, -1, -1):
        if s[i] == ' ':
            break
        length += 1
    return length

More from this blog

C

Chatmagic blog

2894 posts