Missing Number
You are given all numbers between 1,2,…,n except one. Your task is to find the missing number.
Input:- The first input line contains an integer n. The second line contains n−1 numbers. Each number is distinct and between 1 and n (inclusive).
Output:- Print the missing number.
Constraints:-
2≤n≤2⋅10^5
Example:-
Input:
5
2 3 1 5
Output:
4
Code:-
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class MissingNumber {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<Integer,Boolean> map=new HashMap<>();
for(int i=0;i<n-1;i++){
int val=sc.nextInt();
map.put(val,true);
}
for(int i=1;i<=n;i++){
if(!map.containsKey(i)){
System.out.println(i);
break;
}
}
}
}
Comments
Post a Comment
if you have any doubts let me know.