Find the Missing Number in Array 2
Get an array of Integers arr [] with size n and
find the first missing natural number in the array arr[]. The array may contains duplicates.
Example
Input 1:
5
4 5 3 1 6
Output 1:
2
Input 1:
6
4 5 3 1 6 1
Output 1:
2
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class Missing_Number1
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n,bool=0;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
Arrays.sort(arr);
if(arr[0] != 1)
{
System.out.print(1);
}
else
{
for(int i = 1; i<n; i++)
{
if(arr[i]!=arr[i-1]+1 && arr[i]!=arr[i-1])
{
System.out.print(arr[i-1]+1);
bool = 1;
break;
}
}
}
if(bool==0)
{
System.out.print(arr[n-1]+1);
}
}
}