Given an array of size n, we can 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 can solve this problem using two loops:
i
traverses the entire array.j
traverses the remaining array from the i+1
position.i
and j
are equal, then we will break the inner loop and continue with the outer loop.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.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.
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 isDuplicateFound:=false // 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 break } } // if duplicate found after inner loop breaks, // continue with the next iteration of outer loop if isDuplicateFound { continue } // 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 fmt.Println(resultArray) }
Time Complexity :
RELATED TAGS
CONTRIBUTOR
View all Courses