find the duplicates

2 Ways to Find the Duplicates in Array in O(n) time

Given an input array of integers, your goal is to find the duplicates present in the array in an effective way using Java Collections HashSet and HashMap. Note, you need to achieve this in O(n) time i.e., you should be able to find the results by traversing through the array only once.

Algorithm 1 – Using HashSet

Example 1: Find the duplicates using HashSet

Output

Time Complexity – Single Traversal – O(n)

Space Complexity – O(1)

Now let us see the second way to find duplicates using HashMap. Below is the algorithm for the same.

Algorithm 2: Using HashMap

Example 2: Find the duplicates using HashMap

Output

Time Complexity – Single Traversal – O(n)

Recommended Posts

Reference

Leave a Reply

avatar
  Subscribe  
Notify of