Code – Find the smallest positive integer in an array


Hi,

Post your “optimised” codes in the comment section.

import java.util.Arrays;
public class Solution {

    public int solution(int[] A){

        int smallest = 1;
        int count = A.length;
        Arrays.sort(A);

        for (int i = 0; i < A.length; i++){

            if (A[i] >= 0){ //start with positive numbers

                count = i +1;

                if (count < A.length) {

                    if (A[i] == A[count]){
                        //do nothing if consecutive numbers are same
                    }
                    else if (A[i] + 1 != A[count]) {
                        smallest = A[i] + 1;
                        return smallest;
                    }
                }else{
                    smallest = A[i] + 1;
                }
            }
        }

        return smallest;
    }

    public static void main (String args[]){
        int ans = new Solution().solution(new int[]{-1, -5, 10 , 15 ,25 , 4, 9, 6, 5, 5, 5, 6, 6, 6, 6, 6,1 , 2 , 3 , 4 , 5, 5, 7, 8, 10});
        System.out.println("Solution: " + ans);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s