Remove Duplicates from Unsorted Array

Given an unsorted array of integers. Write a code to remove duplicates from unsorted array.

For example:

Input   :{5, 1, 2, 6, 4, 4, 5}
Output :{5, 1, 2, 6, 4}

In this example, 4 and 5 appear multiple times in an input array.

In the output, All the duplicates are removed and we have printed only distinct elements of an array.

Remove Duplicates from an Unsorted Array

Remove Duplicates from an Unsorted Array

In this tutorial, I am going to discuss how we can remove duplicate elements from unsorted array using multiple approaches. Also, we will discuss the time complexities and java code  for each approach.

I have added a video tutorial at the end of this post.

Programming Video Tutorials

Remove duplicates from a sorted linked list

Remove duplicates from sorted array in-place

Remove Duplicates from Unsorted Array Java Code

How to remove duplicate elements from an array? The simplest way to remove duplicates is by sorting an array.

We first sort an array. Once the array is sorted, We can easily remove duplicates by comparing current element with the next element of an array.

The time complexity of this approach is O(nlogn) and it’s space complexity is O(1).

Sorting Algorithms and their Time Complexities

Remove Duplicates from an Unsorted Array by using HashMap

The idea here is to first count each number and it’s occurrences in an array. Once we know the number and it’s count we can easily remove duplicates from an array.

Here, I am using HashMap to store number and it’s count. So, the array element is the key and it’s count is the value. Traverse an array and put each element and it’s count. Once the map is created, print all the keys which is unique elements present in an array.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Find first non-repeating character in a string

Remove Duplicates from an Unsorted Array by using Set

Set does not allow duplicates. By using the property of a set data structure, we can remove duplicates from an array.

Traverse an array and put the array elements in a set. Once the traversal is complete, print all the elements present in a set.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Find the element that appears once in a sorted array

Remove duplicates from an unsorted array – video tutorials

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.