package main import "fmt" func firstNonRepeatingChar(s string) int { count := make(map[rune]int) for _, ch := range s { count[ch]++ } for i, ch := range s { if count[ch] == 1 { return i } } return -1 } func main() { fmt.Println(firstNonRepeatingChar("swiss")) }
The string "swiss" has characters: s(0), w(1), i(2), s(3), s(4). Counts: s=3, w=1, i=1.
The code counts frequencies first, then iterates through the string, finding 'w' at index 1 has count 1, so returns 1.
package main import "fmt" func firstNonRepeatingChar(s string) int { count := make(map[rune]int) for _, ch := range s { count[ch]++ } for i, ch := range s { if count[ch] == 1 { return i } } return -1 } func main() { fmt.Println(firstNonRepeatingChar("aabbcc")) }
All characters in "aabbcc" appear twice, so no non-repeating character exists.
The function returns -1 in this case.
package main import "fmt" func firstNonRepeatingChar(s string) int { count := make(map[int]int) for _, ch := range s { count[ch]++ } for i, ch := range s { if count[ch] == 1 { return i } } return -1 } func main() { fmt.Println(firstNonRepeatingChar("hello")) }
In Go, rune is an alias for int32, but the map is map[int]int. int and int32 are different types, so count[ch] (ch rune) causes a compilation error: cannot use rune (type int32) as type int in map index.
package main import "fmt" func firstNonRepeatingChar(s string) int { count := make(map[rune]int) for _, ch := range s { count[ch]++ } for i, ch := range s { if count[ch] == 1 { return i } } return -1 } func main() { fmt.Println(firstNonRepeatingChar("aƔa")) }
The string "aƔa" has characters: 'a' at 0 and 2, 'Ɣ' at 1.
'a' appears twice, 'Ć”' once.
The first non-repeating character is 'Ć”' at index 1.
package main import "fmt" func countUniqueNonRepeating(s string) int { count := make(map[rune]int) for _, ch := range s { count[ch]++ } uniqueCount := 0 for _, v := range count { if v == 1 { uniqueCount++ } } return uniqueCount } func main() { fmt.Println(countUniqueNonRepeating("abracadabra")) }
In "abracadabra", character counts are: a=5, b=2, r=2, c=1, d=1.
Characters 'c' and 'd' appear exactly once.
So the count is 2.
