Write a java program to find the smallest positive integer not present in an array
I do find this question while practicing #Java_Programming on #codility. There are many solution to this question but I think the best one I have came across is using hashSet. It's a simple combination than using array login so thought of sharing it.
Before proceeding ahead in order to understand this #problem_statement better here are few examples:
given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Logic:
We are storing all the element of the input array in #HashSet and we will define int smallint =1; we will use while loop to loop all the element of an array and compare it with smallint =1 value. if the value is equal to smallint =1 then we are incrementing value by 1 and print the result or we will print smallint =1
#Java_Code
package Others;
import java.util.*;
public class smallestpossibleNumberInArray {
public static int solution(int[] a){
HashSet<Integer> hashSet = new HashSet<Integer>();
int smallint =1;
for (int i = 0; i < a.length; i ++){
hashSet.add(a [i]);
}
while (hashSet.contains(smallint)){
smallint ++;
}
return smallint;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter the array");
Scanner sc = new Scanner(System.in);
int [] A = new int [5];
for (int i = 0; i < A.length; i ++){
System.out.println("please enter the number");
A[i] = sc.nextInt();
}
sc.close();
// output of the function
System.out.println("NextSmallestpositiveNumber in an array is " +solution(A) );
}
}
#output
Please enter the array
please enter the number
-22
please enter the number
0
please enter the number
-11
please enter the number
-2
please enter the number
1
NextSmallestpositiveNumber in an array is 2
#Java #Smallest_Next_Positive_Number_In_an_Array #Selenium #Hashset
#java_programming #algorithm #code_to_test #data_structure
List allow duplicate element while Hashset does not. If you don't want to allow null as well I think TreeSet is a best choice
Any reason for using hashset instead of list?