C Program To Find Duplicate Element In Array Time Complexity O(n), Space Complexity O(1)

// duplicates in O(n) time
#include <stdio.h>
#include <stdlib.h>
// Function to print duplicates
void printRepeating(int arr[], int size)
{
	int i;
	printf("The repeating elements are: \n");
	for (i = 0; i < size; i++) {
		if (arr[abs(arr[i])] >= 0)
			arr[abs(arr[i])] = -arr[abs(arr[i])];
		else
			printf(" %d ", abs(arr[i]));
	}
}
// Driver Code
int main()
{
	int arr[] = { 5, 2, 7, 5, 7, 6, 6 };
	int arr_size = sizeof(arr) / sizeof(arr[0]);
	printRepeating(arr, arr_size);
	getchar();
	return 0;
}

Output:

The repeating elements are:
5  7  6

Leave a Comment