Find All Duplicates in an Array

How to find all duplicates in an array without using extra space?

Given an array of integers, the integers are in the range of 1 ≤ a[i] ≤ n (n = size of array). In this Array, some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

We have to solve this problem without using extra space and in O(n) time complexity.

For Example:

Input: [4, 3, 2, 7, 8, 2, 3, 1]

Output: [2, 3]

Find All Duplicates in an Array

This problem is very simple, if extra space is allowed. If extra space is allowed, we can use Set, HashMap or other data structure to find all the elements that appear twice in this array.

But in this problem, we have to find duplicates in O(n) time and O(1) extra space.

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

Programming Video Tutorials

Programming Questions on Array

Interview questions for practice

Find All Duplicates in an Array – Java Code

In this example, we are going to solve this problem without using extra space.

The idea here is to traverse an array and take each array element at a time. Then visit the index which is array element minus one and flip the number at that index from positive to negative. If the number present at that index is already negative then the current element is already appeared in this array. So, This number is a duplicate number. Similarly, we repeat this process until the array is traversed completely.

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

Tagged , , . Bookmark the permalink.

About WebRewrite

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