How long is the last word? Words are separated by spaces, and the string may have trailing ones.
lengthOfLastWord("Hello World") // 5lengthOfLastWord(" fly me to the moon ") // 4The standard library answer
func lengthOfLastWord(s string) int { var splits = strings.Split(strings.TrimSpace(s), " ") return len(splits[len(splits)-1])}TrimSpace removes the trailing spaces that make the naive version wrong, and
after that the last field is the last word. Correct, including the awkward case
of runs of spaces in the middle — Split yields empty strings for those, but
never as the final element once the string is trimmed.
The one-pass version
Split allocates a slice of every word to use exactly one of them. Walking
backwards uses none:
func lengthOfLastWord(s string) int { i := len(s) - 1
for i >= 0 && s[i] == ' ' { // skip trailing spaces i-- }
length := 0 for i >= 0 && s[i] != ' ' { // count the word length++ i-- }
return length}worst case, space, and it usually touches only the last few characters rather than all of them.
Worth noticing
This is the rare problem where the library version and the hand-written version
are both defensible, and for opposite reasons. strings.Fields is what to write
in production: shorter, obviously correct, and someone else maintains the edge
cases. The backwards scan is what an interviewer is asking for: it demonstrates
that you noticed the work being wasted.
Knowing which answer the question wants is part of the question.