HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Find missing number from list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
findnumbermissinglistfrom

Problem

I was asked a question in an interview the other day:


You have an array list of numbers from 1 to 100, the problem is that
one number is missing. How would you find that number?

This is a mock of the question. The code seems to work.

Could you give me some feedback?

private int count;

public void find() {
    //prep for question
    List ints = new ArrayList();
    for (int i = 0; i < 100; i++) {
        ints.add(i);
    }
    ints.remove(67);

    //find the missing number
    for (Integer i : ints) {
        if (i != count) {
            System.out.println(count);
            count++;
        }
        count++;
    }
}


Output = 67

Solution

This is a very common interview question. However, your algorithm won't suffice: the array may be unsorted.

The method is to find the sum of the numbers in the array and then subtract it from the sum of numbers from 1 through 100. What's left over is what is missing from a complete list 1..100.

Sum of natural numbers \$1..N\ = \dfrac{N(N+1)}{2}\$.

Context

StackExchange Code Review Q#18424, answer score: 15

Revisions (0)

No revisions yet.