Count Words Go
Fast recall
Quick revision
Core answer
Whether you understand Count Words Go beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
The word count, executed:
words := strings.Fields("hello world go")
len(words) // 3 — verified
// With a delimiter
parts := strings.Split("a,b,c", ",")
len(parts) // 3The character frequency counter:
freq := make(map[rune]int)
for _, r := range "hello" { freq[r]++ }
// freq: h:1 e:1 l:2 o:1The word-frequency counter (the composition):
freq := make(map[string]int)
for _, w := range strings.Fields(text) {
freq[strings.ToLower(w)]++ // case-normalized
}The tools by job: Fields for word boundaries (whitespace runs — any space/tab/newline). Split for an exact delimiter. map[K]int for the count — the counter pattern from the hash-map topic. strings.ToLower for normalization, strings.TrimPunct for cleaning.
The counting idiom (the increment): freq[key]++ works on the zero value (an absent key reads as 0 — increment works without initialization). That single language feature is why the Go counter is one line.
Count Words Go
Direct Answer
strings.Fields splits on whitespace → len for the count. strings.Split for a specific delimiter. map[string]int for frequencies. Verified: strings.Fields("hello world go") → 3 words.
Deep Dive & Architecture
The Fields vs Split distinction (the DSA module's strings topic covers it deeper): Fields is the boundary-based splitter — any whitespace run is one separator, leading/trailing dropped. Split is the mark-based one — an exact string, with empty results between adjacent delimiters. Counting words = Fields; counting CSV fields = Split.
The rune iteration's correctness: for _, r := range s decodes UTF-8 as it iterates — the frequency counter is Unicode-correct (é counted once, not as two byte fragments). The byte form (for i := 0; i < len(s); i++) counts the ENCODING, not the characters — the strings topic's core distinction applied to counting.
The pattern's O: O(n) per pass (the split allocates the words; the counting builds the map). The space: the map's size is bounded by the distinct words/characters — for text processing, the map can approach n entries (all-unique words), which is honest: you can't count without remembering what you've seen.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Count Words Go in a real project?
- How would you compare Count Words Go with an alternative?
- What is a common mistake when using Count Words Go?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.