↓Skip to main content
  1. LeetCode/

LeetCode 58: Length of Last Word

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-05-11

  • Submissions: Accepted ×3 → Wrong Answer → Accepted ×3 → Runtime Error → Accepted ×3

Approach
#

s.split() drops leading and trailing spaces and merges runs of spaces, so its last element is the last word (String Template 6). Without splitting everything, scan from the end: skip spaces, then count non-spaces.

My Attempts
#

One 2022-05 version used split(" ")[-1], whose last element is empty when the string ends with a space: "a " returned 0 instead of 1. A 2022-08 rewrite put the -1 inside split(-1) (TypeError).

Solution
#

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i = len(s) - 1
        while s[i] == " ":
            i -= 1
        n = 0
        while i >= 0 and s[i] != " ":
            n += 1
            i -= 1
        return n

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • The string may end with spaces; split(" ")[-1] yields an empty string.

Interview Explanation
#

From the end I skip trailing spaces and count the following non-space characters, in O(1) space; taking the last element of split() also works.

Related

LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1