Repeated numbers! Need help understanding the following function.

"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
1
2
3
4
(arr[abs(arr[i])] >= 0) 
    arr[abs(arr[i])] = -arr[abs(arr[i])]; 
    else
    cout << abs(arr[i]) << " "; 

does.

full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  // C++ code to find 
// duplicates in O(n) time 
#include <bits/stdc++.h> 
using namespace 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  
Last edited on
It doesn't work.

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.
Last edited on
Topic archived. No new replies allowed.