Is it possible to remove duplicates from an unsorted array in O(n) time, O(1) space complexity, using the Floyd's tortoise and hare algorithm?

989 views Asked by At

Is it possible to remove duplicates from an unsorted array in O(n) time, O(1) space complexity, using the Floyd's tortoise and hare algorithm? Consider the array [3,1,3,4,2]. After removing duplicates, the function "remove_dups" must return [3,1,4,2]. Also, the function should work on negative integers in the array.

1

There are 1 answers

2
Avishek Bhattacharya On

Yes it is possible. The idea is to consider array items as linked list nodes. Any particular index is pointing to the value at that index.

And you will see that there is loop in case of duplicate, two indexes will have same value, and they will form a cycle just like in the image given below.

Example:

1->2->3->4->5->6->3

So we can find the entry point of cycle in the linked list and that will be our duplicate element.

Source : https://www.geeksforgeeks.org/find-duplicates-constant-array-elements-0-n-1-o1-space/