7. Find missing and Repeating elements
7. Find missing and Repeating elements
Problem link :- click here
package program;
public class Searching__7
{
/*
Given an unsorted array arr[] of size n of positive integers. One number
'A' from set{1, 2, 3, 4, 5, ....... n} is missing and one number 'B' occurs
twice in array. Find these two numbers
We have solved a similar question in array where we are asked to find the
duplicate elements in the array which contains only elements from 0 to n-1
here the only difference is elements are from 0 to n
*/
static int[] findTwoElements(int arr[], int n)
{
int ans[] = new int[2];
//first check which element is repeating
for(int i=0; i<n; i++)
{
if( arr[ Math.abs(arr[i]) - 1 ] > 0 )
arr[ Math.abs(arr[i]) - 1 ] = -arr[ Math.abs(arr[i]) - 1 ];
else
{
ans[1] = Math.abs( arr[i] );
break; //because only one element is repeated
}
}
for(int i=0; i<n; i++)
{
if(arr[i] > 0)
{
ans[0] = i + 1;
break;
}
}
return ans;
}
public static void main(String[] args)
{
int arr[] = {1, 3, 3};
int ans[] = findTwoElements(arr, arr.length);
System.out.println("Missing and Repeating elements are : ");
for(int i=0; i<ans.length; i++)
System.out.print(ans[i] + " ");
}
}
Time complexity :- O(n)
Space complexity :- O(1)
Comments
Post a Comment