0
0
GoProgramBeginner · 2 min read

Go Program to Remove Duplicates from String

In Go, you can remove duplicates from a string by using a map to track seen characters and building a new string with only unique characters, for example: seen := make(map[rune]bool); for _, ch := range input { if !seen[ch] { seen[ch] = true; result += string(ch) } }.
📋

Examples

Inputhello
Outputhelo
Inputbanana
Outputban
Input
Output
🧠

How to Think About It

To remove duplicates from a string, think of checking each character one by one and remembering which characters you have already seen. If a character is new, add it to the result. If it is already seen, skip it. This way, you keep only the first occurrence of each character.
📐

Algorithm

1
Get the input string.
2
Create an empty map to keep track of characters seen.
3
Create an empty string to store the result.
4
For each character in the input string:
5
Check if the character is in the map.
6
If not, add it to the map and append it to the result string.
7
Return the result string.
💻

Code

go
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))
}
Output
ban
🔍

Dry Run

Let's trace the input "banana" through the code

1

Initialize variables

seen = {}, result = ""

2

Process first character 'b'

'b' not in seen, add 'b' to seen and result = "b"

3

Process second character 'a'

'a' not in seen, add 'a' to seen and result = "ba"

4

Process third character 'n'

'n' not in seen, add 'n' to seen and result = "ban"

5

Process fourth character 'a'

'a' already in seen, skip

6

Process fifth character 'n'

'n' already in seen, skip

7

Process sixth character 'a'

'a' already in seen, skip

8

Return result

result = "ban"

CharacterSeen Map KeysResult String
bbb
ab,aba
nb,a,nban
ab,a,nban
nb,a,nban
ab,a,nban
💡

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

Using a byte array and index
go
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"))
}
This method uses byte slices for efficiency but works only with ASCII characters.
Using strings.Builder for better performance
go
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"))
}
Using strings.Builder improves performance when building strings in Go.

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.

ApproachTimeSpaceBest For
Map with string concatenationO(n)O(n)Simple and clear code
Map with byte sliceO(n)O(n)ASCII strings, better performance
Map with strings.BuilderO(n)O(n)Large strings, best performance
💡
Use a map to track seen characters for quick duplicate detection.
⚠️
Trying to remove duplicates by modifying the string directly without tracking seen characters causes incorrect results.