What is wrong with my Java solution to Codility MissingInteger?

returns the minimal positive integer that does not occur in A.

So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1.

I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the indexes of the given array, and then removing keys based on the values it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array.

So, for example, if you iterate from 1 to Integer.MAX_VALUE, inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at O(n).


I have done the answer inspired by the answer of Denes but a simpler one.

int counter[] = new int[A.length];

// Count the items, only the positive numbers
for (int i = 0; i < A.length; i++)
    if (A[i] > 0 && A[i] <= A.length)
        counter[A[i] - 1]++;

// Return the first number that has count 0
for (int i = 0; i < counter.length; i++)
    if (counter[i] == 0)
        return i + 1;

// If no number has count 0, then that means all number in the sequence
// appears so the next number not appearing is in next number after the
// sequence.
return A.length + 1;

Here is my answer, got 100/100.

import java.util.HashSet;

class Solution {
    public int solution(int[] A) {
        int num = 1;
        HashSet<Integer> hset = new HashSet<Integer>();

        for (int i = 0 ; i < A.length; i++) {
            hset.add(A[i]);                     
        }

         while (hset.contains(num)) {
                num++;
            }

        return num;
    }
}

Tags:

Java