Golang Program that Removes Duplicates Using Nested Loops


Removing duplicates from a slice or an array is a common problem in programming. One of the ways to solve this problem in Golang is by using nested loops. In this article, we will write a Golang program that removes duplicates from a slice using nested loops.

Understanding the Problem

Before writing the program, let's understand the problem statement. Suppose we have a slice with some duplicate elements −

numbers := []int{1, 2, 3, 1, 4, 2, 5}

Our task is to remove the duplicate elements from this slice and get the unique elements. The final slice should look like this −

uniqueNumbers := []int{1, 2, 3, 4, 5}

Solution using Nested Loops

To solve this problem, we can use nested loops to compare each element of the slice with the other elements and remove duplicates. Here is the Golang code to remove duplicates from a slice using nested loops −

Example

package main

import "fmt"

func removeDuplicates(numbers []int) []int {
   // Use a map to keep track of unique elements
   unique := make(map[int]bool)
   result := []int{}

   // Loop over the slice and remove duplicates
   for _, num := range numbers {
      if !unique[num] {
         unique[num] = true
            result = append(result, num)
      }
   }
   return result
}

func main() {
   // Test the removeDuplicates function
   numbers := []int{1, 2, 3, 1, 4, 2, 5}
   uniqueNumbers := removeDuplicates(numbers)
   fmt.Println(uniqueNumbers)
}

Output

1 2 3 4 5]

In the above code, we have created a removeDuplicates function that takes a slice of integers as input and returns a new slice with unique elements. The function uses a map to keep track of unique elements and a loop to remove duplicates. The loop iterates over the input slice and checks if the current element is already present in the map. If the element is not present in the map, it is added to the result slice and marked as seen in the map.

Conclusion

In this article, we have learned how to remove duplicates from a slice using nested loops in Golang. We have seen how to use a map to keep track of unique elements and a loop to remove duplicates. This method is efficient for small slices, but for large slices, there are more efficient algorithms available.

Updated on: 18-Apr-2023

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements