Monday, February 3, 2025

Length of Last Word

    Profile Pic of Akash AmanAkash Aman

    Updated: February 2025

    Length of Last Word
    easy

    💡 Intuition

    • The idea is to iterate through each character while using a flag to track whether a word has started and continue counting until a space (" ") is encountered.

    hloIteration 1eIteration 2Iteration 3length = 0wlorldhloewlorldlength = 0hloewlorldlength = 1Iteration 4hloewlorldlength = 2Iteration 5hloewlorldlength = 3Iteration 6hloewlorldlength = 4Iteration 7hloewlorldlength = 5Iteration 8hloewlorldlength = 5+1+1+1+1+1

    🚀 Solution

    go
    func lengthOfLastWord(s string) int {
        var end rune = ' ';
    	var count int = 0;
    	for i := len(s) - 1; i >= 0; i-- {
    		if rune(s[i]) == end && count > 0 {
    			return count
    		}
    
            if rune(s[i]) != end {
                count++
            }
    	}
    
    	return count;
    }

    ⏳ Time Complexity

    • Since we are taking single loop for the array of length n, the time complexity will be O(n)

    © 2026 Akash Aman | All rights reserved