Home Arrays Print 2 repeating elements in a given array.

Print 2 repeating elements in a given array.

by nikoo28
0 comment 2 minutes read

Question: Given an array with n+2 elements, all elements of the array are in range 1 to n and also all elements occur only once except 2 numbers which occur twice. Find those 2 repeating numbers.

Input: arr[] = {6, 2, 6, 5, 2, 3, 1}
Output: 6 2

One simple way is to scan the complete array for each element of the input elements. That means use two loops. In the outer loop, select elements one by one and count the number of occurrences of the selected element in the inner loop. If an element occurs twice, we can simply print that element.

Here is a sample code for the above method:-

void printRepeatingElements(int arr[], int n)
	int i,j;

	//outer loop
		//inner loop
			//if we find  repeating element
			//then print it directly
			if(arr[i] == arr[j])
				printf("%d ",arr[i]);

Time Complexity:- O(n2)
Space Complexity:- O(1)

Click here for Method 2 that involves count array and a better time complexity.

Click here for Method 3 that involves XOR operation and a even better time complexity.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More