0

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 Answers1

0

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/

Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53
  • Yea, I understand that it is possible to "find" the duplicate element. But my doubt is can we remove those duplicates in-place or without using extra space. Like if the array is [ -1, -2, 1, -1, 2] then the function must return [-1, -2, 1, 2] –  Aug 11 '20 at 08:13
  • If you can find you can drop one of the element but the problem with array is that it's contiguous memory so even if you drop the element the memory location cannot be freeed. – Avishek Bhattacharya Aug 11 '20 at 08:32