String: April Fool -POTD

String: April Fool -POTD

Day 8/75:

Question: Length of Last Word -(Easy)

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.

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.        

Introduction:

Question require to determine the length of the last word in a given string s. This problem is of identifying and computing the length of the last word in the string.

Intuition:

Our first step in tackling this problem is to traverse the string from end to start and identify the last word. We can do this by iterating through the characters of the string in reverse order and counting the characters until we encounter a space. Once we encounter a space, we know that we have reached the end of the last word, and we can return its length.

Approach:

We can implement this approach using a simple loop that iterates through the characters of the string in reverse order. We initialize a variable count to keep track of the length of the last word encountered. As we iterate through the string, we increment the count variable until we encounter a space character. Once we encounter a space character and count is greater than zero, we break out of the loop and return the value of count as the length of the last word.

Code:

Article content


Time and Space Complexity:

  • Time Complexity: O(n), where n is the length of the input string s.
  • Space Complexity: O(1), as we only use a constant amount of extra space regardless of the input size.

Conclusion:

The implemented solution efficiently computes the length of the last word in the given string by traversing the string in reverse order and counting the characters until a space is encountered. By leveraging this approach, we achieve linear time complexity, making the solution suitable for large input sizes.


To view or add a comment, sign in

Others also viewed

Explore topics