4

I am given a supposedly consecutive array such as this:

{4,5,7,8,9,10} // missing 6

And I am supposed to efficiently find the missing 6.

I have thought of doing a binary search, and checking the mid +1, mid -1.

But I keep thinking there would be so many base cases. I keep failing...

This shouldn't be such a hard problem but I do not know why I am struggling so hard :/

Could someone guide me through this one??

Thanks so much guyz

6
  • Although you have already received several possible answers, I think it's worth noting that if you're struggling with one approach, you'll need to move on to figuring out a different one. A binary search likely isn't what they are looking for there. There are a lot of tricks to address the issue, but the simplest one to understand (IMHO) involves a single for loop. Commented May 10, 2015 at 5:42
  • use binary search... that is the best you can do... First chapter in Programming Pearls.. Commented May 10, 2015 at 5:54
  • 1
    The array in this question is sorted, while the array in referenced question is explicitly shuffled. This allows for a quicker, binary-search solution. Commented May 10, 2015 at 6:11
  • it's true that if the array is sorted, the solution can be given in log(n) time using binary search Commented May 10, 2015 at 6:26
  • Yes, the array is sorted. That's why I avoided the linear search Commented May 10, 2015 at 6:35

2 Answers 2

2

Always keep it simple buddy . You can always do this in N time complexity.

int[] arr = new int[]{4,5,7,8,9,10};
        int missing=0;
        for(int i=0;i<arr.length;i++)
        {  

            int x = arr[++i];
            int y = arr[i] +1;

          if(x != y )
          {
              missing = y;
              break;
          }
        }

        System.out.println(missing);
Sign up to request clarification or add additional context in comments.

2 Comments

Your program return incorrect result when i input {4,5,6,7,8,10}.
1

In one linear pass find the smallest element, the largest element and the sum of all the elements.

Knowing the smallest and the largest you can compute the sum of all the numbers if nothing was missing (it's a sum of an arithmetic progression). Subtracting the actual sum from it will give you the missing number.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.