7. Distinct Words

Complete the countDistinctWords function using a map. It should take a slice of strings and return the total count of distinct words across all the strings. Assume words are separated by spaces. Casing should not matter. (e.g., "Hello" and "hello" should be considered the same word).

For example:

messages := []string{"Hello world", "hello there", "General Kenobi"}
count := countDistinctWords(messages)

count should be 5 as the distinct words are "hello", "world", "there", "general" and "kenobi" irrespective of casing.

circle-info

Tips

Solution

My Solution

solution.go
package main
import "strings"

func countDistinctWords(messages []string) int {
	holder := make(map[string]struct{})
	count:=0

	for _,words:= range messages{
		sepWords:= strings.Fields(words)
		for _, word:= range sepWords{
			lowered:= strings.ToLower(word)
			if _, ok:=holder[lowered]; !ok{
				holder[lowered] = struct{}{}
				count++
			}
		}
	}
	return count
}

Optimized Solution

circle-check