Go Program to Remove Duplicates from String
seen := make(map[rune]bool); for _, ch := range input { if !seen[ch] { seen[ch] = true; result += string(ch) } }.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" ) func removeDuplicates(s string) string { seen := make(map[rune]bool) result := "" for _, ch := range s { if !seen[ch] { seen[ch] = true result += string(ch) } } return result } func main() { input := "banana" fmt.Println(removeDuplicates(input)) }
Dry Run
Let's trace the input "banana" through the code
Initialize variables
seen = {}, result = ""
Process first character 'b'
'b' not in seen, add 'b' to seen and result = "b"
Process second character 'a'
'a' not in seen, add 'a' to seen and result = "ba"
Process third character 'n'
'n' not in seen, add 'n' to seen and result = "ban"
Process fourth character 'a'
'a' already in seen, skip
Process fifth character 'n'
'n' already in seen, skip
Process sixth character 'a'
'a' already in seen, skip
Return result
result = "ban"
| Character | Seen Map Keys | Result String |
|---|---|---|
| b | b | b |
| a | b,a | ba |
| n | b,a,n | ban |
| a | b,a,n | ban |
| n | b,a,n | ban |
| a | b,a,n | ban |
Why This Works
Step 1: Use a map to track characters
The map seen stores characters as keys to quickly check if a character appeared before.
Step 2: Iterate over each character
Looping through the string lets us check each character one by one.
Step 3: Build result with unique characters
Only characters not in seen are added to the result string, ensuring no duplicates.
Alternative Approaches
package main import "fmt" func removeDuplicates(s string) string { result := []byte{} seen := make(map[byte]bool) for i := 0; i < len(s); i++ { if !seen[s[i]] { seen[s[i]] = true result = append(result, s[i]) } } return string(result) } func main() { fmt.Println(removeDuplicates("hello")) }
package main import ( "fmt" "strings" ) func removeDuplicates(s string) string { seen := make(map[rune]bool) var builder strings.Builder for _, ch := range s { if !seen[ch] { seen[ch] = true builder.WriteRune(ch) } } return builder.String() } func main() { fmt.Println(removeDuplicates("banana")) }
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through each character once, so time grows linearly with input size.
Space Complexity
The map stores seen characters, which can be up to the size of the input string in the worst case.
Which Approach is Fastest?
Using strings.Builder is faster for large strings compared to string concatenation, but all approaches are O(n) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Map with string concatenation | O(n) | O(n) | Simple and clear code |
| Map with byte slice | O(n) | O(n) | ASCII strings, better performance |
| Map with strings.Builder | O(n) | O(n) | Large strings, best performance |