Efficient TypeScript Method: Finding Length of Last Word in a String

Efficient TypeScript Method: Finding Length of Last Word in a String

LeetCode data structures and algorithms.

ยท

2 min read

Hi there! In this subsequent series, will solve a simple challenge from leetcode - length of the last word. This challenge will mostly involve the usage of strings, arrays and their methods.
Below is the challenge at hand:
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.

function lengthOfLastWord(s: string): number {

};

According to the challenge, the function lengthOfLastWord should return the length of the last word in string s. To solve this challenge, we should first remove all white spaces existing in the string s parameter.

function lengthOfLastWord(s: string): number {
    s.trim()
};

We'll then convert the string to an array using the JavaScript string method split()

function lengthOfLastWord(s: string): number {
    s.trim().split(' ')
};

After the string s is split, we'll now use the pop() method to remove the last element from an array

function lengthOfLastWord(s: string): number {
    s.trim().split(' ').pop()
};

In the following step, we will make use of TypeScript's Optional Chaining operator and Nullish Coelicing operator.

  1. Optional Chaining operator - The optional chaining operator (?.) allows you to access properties or call methods of an object, but it guards against errors that might occur if the object is null or undefined. It essentially checks if the left-hand side of the expression is null or undefined before attempting to access the property or call the method on it. If the left-hand side is null or undefined, the entire expression evaluates to undefined.
  1. Nullish Coelicing operator - The nullish coalescing operator (??) is used to provide a default value when the left-hand side of the expression is null or undefined. It evaluates to the left-hand side value if it's not null or undefined, otherwise, it evaluates to the right-hand side value.
function lengthOfLastWord(s: string): number {
    return s.trim().split(' ').pop()?.length?? 0;
};

To summarize, the code takes an input string s, splits it into an array of words using spaces as separators, retrieves the last word from the array, and calculates the length of that word. If the input string is empty or does not contain any words, the length of the last word is considered to be 0. The final result, which is the length of the last word (or 0 if the input string is empty), is then printed to the console.

ย