Finding duplicates in an Array

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
int arr[] = {1,4,1,4,5,5};
int n= sizeof(arr)/sizeof(arr[0]);
int i;
    cout << "The repeating elements are:" << endl;
    for (i = 0; i < n; i++) {
         // I have no idea how this works...
         int k=abs(arr[i]);
         if (arr[k] >= 0)
            arr[k] = -arr[k];
         else
            cout << k<< " ";
    }


}

This is the solution from a website.
I didn’t understand what exactly k returns.
your help is highly appreciated :smile:

I don’t know that it actually ‘finds the duplicates in arrays’ in any sort of general sense. This code is a memory safety disaster that should never be used.

This code assumes that the array will only have entries that are positive and that the array will only have entries with values strictly less than the total length of the array.

This code flips the value at index k from positive to negative the first time the value k is encountered. The code then reports a duplicate to cout if it finds a negative value at index k from a subsequent value.

If the entries of the array can be negative or positive this approach won’t work.

And this is a great example of how you can make terrible C++ code that can overwrite data that you shouldn’t. You should never blindly write past the end of an array in C++. This is very memory unsafe code.

1 Like

Thankyou so much for the feedback @JeremyLT
I will roger that! :grin:

1 Like