Algorithm Question: Return the length of the last word

Woodelin florveus
2 min readJul 1, 2021

Problem Statement

In this particular algorithm, we’ll go over the length of the last word question. This algorithm can be found on leet code. I had a few tries on this question. I did not receive success until I did a bit more research on how I was going to get the output. The question states, “ Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word in the length does not exist, return 0”. The question explained the problem clearly and concisely which allowed me to come up with good strategies to solve the algorithm.

Constraints and Challenges

During this algorithm, I faced a few problems. Most of my strategies did not go through therefore my submission was futile. One strategy I thought would work was to split the string loop through each word and return the last word of the loop. It seemed like a reasonable and great solution however it did not go well with Leetcode submissions. Pinned up against unique outputs, it seems my solution was not dynamic, or I was just missing a step.

Solution

Over time I refactored my solution to a more manageable and dynamic one. The resource I was missing for a better outcome was trim. In one of my submissions, I noticed that my solution was not able to solve issues for the white space. Therefore adding trim served a part in getting accepted. The solution is a simple two-liner. I created a variable where I was able to trim and split the string. Furthermore, I return the last word and add a conditional if the string is left empty. Before looking below I suggest you take another crack at it.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

What are your thoughts?