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 mainimport "fmt"func removeDuplicates(arr []int) []int {// declare an empty arrayresultArray := []int{}// length of the arrayn:= len(arr);// Outer for loop to traverse the entire arrayfor i := 0; i < n; i++ {// variable to keep track of duplicateisDuplicateFound:=false// inner loop to traverse remaining array from next element to ifor j := i+1 ; j < n; j++ {// check for duplicateif arr[j] == arr[i] {// if duplicate found break the inner loopisDuplicateFound = truebreak}}// if duplicate found after inner loop breaks,// continue with the next iteration of outer loopif isDuplicateFound {continue}// add present element at iresultArray = append(resultArray, arr[i])}// return the array without duplicatesreturn resultArray}//main function definationfunc main() {// provide array with duplicate elementsarr := []int{11, 12, 11, 22, 12, 33, 22}// calling removeDuplicates functionresultArray := removeDuplicates(arr)// printing the answerfmt.Println(resultArray)}
Time Complexity :