Golang Program that Removes Duplicates Using Nested Loops

Given an array of size n. Your task is to remove the duplicates from the array.


Input : array: 1 2 1 2 1 3 2 
Output :1 2 3

Input :array: 10 24 5 10 24
Output :10 24 5

We will use two loops to solve this problem. The first loop i will traverse from 0 to the length of the array. The second loop will traverse from 0 to i-1. This loop is used to make sure that the element at index i has not come before i. If that element has come before, then we come out of the second loop. just after the second loop, we write an if condition which checks if j = = i. If they are equal, it means that the element at index i has not occurred before. So we must append the element to the result array.





// Golang Program that Removes
// Duplicates Using Nested Loops
package main
import "fmt"
func removeDup(a []int, n int) []int {
    // declaring an empty array
    result := []int{}
    // traversing the array
    // from 0 to length of array
    for i := 0; i < n; i++ {
        j := 0 // variable for next loop
        // loop to check if the current
        // element has come before or not
        for ; j < i; j++ {
            if a[j] == a[i] {
                // it means the element
                // has come before, so break
        // it means that the element has not
        // come anytime, so append it in
        // the resultant array
        if j == i {
            result = append(result, a[i])
    return result
func main() {
    // declaring the array
    a := []int{1, 2, 1, 2, 1, 3, 2}
    // size of the array
    n := 7
    // calling the remove duplicates
    // function to get the answer
    result := removeDup(a, n)
    // printing the answer



[1 2 3]

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.