MissingInteger

Find the smallest positive integer that does not occur in a given sequence.


Solution:

Solution to Codility's Missing Integer problem which is from the Codility Lesson 4: Counting Elements and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to find the smallest positive integer that does not occur in a given sequence. You can find the question of this MissingInteger problem in the Codility website.


package Codility.Lesson4;

import java.util.*;

public class MissingInteger {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int input[] = { 3, 4, 4, 6, 1, 4, 4 };
		int result = solution(input);
		System.out.println(result);
	}

	public static int solution(int[] A) {
		// write your code in Java SE 8
		Arrays.sort(A);
		int counter = 0;
		int previous = 0;

		for (int i = 0; i < A.length; i++) {
			if (A[i] > 0) {
				if (previous != A[i]) {
					counter++;
					if (A[i] != counter) {
						return counter;
					}
				}
				previous = counter;
			}
		}
		if (counter >= 0) {
			return counter + 1;
		}
		return 1;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *