Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to remove duplicates from an array using nested loops

Gutha Vamsi Krishna

Given an array of size n, we can remove the duplicates from the array.

Example 1

  • Input array: [1, 2, 1, 2, 1, 3, 2]

  • Output : [1, 2, 3]

Example 2

  • Input array: [10, 24, 5, 10, 24]

  • Output : [10, 24, 5]


We can solve this problem using two loops:

  • The outer loop i traverses the entire array.
  • The inner loop j traverses the remaining array from the i+1 position.
  • At any time while traversing, if elements at positions i and j are equal, then we will break the inner loop and continue with the outer loop.
  • If j reaches the end of the array, then it means we could not find any duplicate elements at position i. Add that element to the resultArray where we store non-duplicate elements.
  • If i reaches the end of array, then it means we traversed the entire array and the return value is resultArray.

Check out the visualization below to understand better.

Given array
1 of 21

Implementation in Go

package main

import "fmt"

func removeDuplicates(arr []int) []int {

	// declare an empty array
	resultArray := []int{}

  	// length of the array
  	n:= len(arr);

  	// Outer for loop to traverse the entire array
	for i := 0; i < n; i++ {

		// variable to keep track of duplicate

		// inner loop to traverse remaining array from next element to i
		for j := i+1 ; j < n; j++ {

			// check for duplicate
			if arr[j] == arr[i] {
				// if duplicate found break the inner loop
        		isDuplicateFound = true
	// if duplicate found after inner loop breaks,
	// continue with the next iteration of outer loop
    if isDuplicateFound {

	// add present element at i
    resultArray = append(resultArray, arr[i])


	// return the array without duplicates
	return resultArray


//main function defination
func main() {

	// provide array with duplicate elements
	arr := []int{11, 12, 11, 22, 12, 33, 22}

  	// calling removeDuplicates function 
	resultArray := removeDuplicates(arr)

	// printing the answer


Time Complexity : O(n2)O(n^2)



View all Courses

Keep Exploring