"Find duplicates in O(n) time and O(1) extra space" on geekesofgeeks is the source of the code below. I watched their video but couldn't understand how it got the repeated numbers. I request the reader to explain how this code does what it
// C++ code to find
// duplicates in O(n) time
#include <bits/stdc++.h>
usingnamespace std;
// Function to print duplicates
void printRepeating(int arr[], int size)
{
int i;
cout << "The repeating elements are:" << endl;
for (i = 0; i < size; i++)
{
if (arr[abs(arr[i])] >= 0)
arr[abs(arr[i])] = -arr[abs(arr[i])];
else
cout << abs(arr[i]) << " ";
}
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 1, 3, 6, 6};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printRepeating(arr, arr_size);
return 0;
}
// This code is contributed
// by Akanksha Rai
Try making the last element of the array 10 instead of 6.
Or just delete the 2.
That code is nonsense if the elements of the array could be any int. (Is there something you haven't told us?) Also, O(1) space it is not if you want to re-use that array, since you would need to make a copy.
I presume they are just using the position in the array to indicate "already taken", by flagging it by turning it negative. But that's only going to work if all elements of the array are assumed to be positive and less than or equal to the largest index of the array.
EDIT: Just found the original code on geeksfor geeks - there is an extra condition on the elements of the array WHICH YOU DIDN'T STATE.