0

There will be an array starting from 1,2,3.... n. If any one number is removed from the array what is the optimun way to find out removed number.

Giri Aakula
  • 123
  • 2
  • 9

3 Answers3

1

The following is just one possible way to find the missing one.

If n is given, then the sum of the series 1 + 2 + 3 + ... + n is,

S =  1 + 2 + 3 + ... + n
  = n * (n + 1) / 2

So, ultimately, you know the value of S. Now sum up all the integers you are given. Let's call it S'. And the difference between S and S', (S - S') is the answer.

This will work even the given integers are in random order. This will not require a binary search where it is required that the integers must be sorted and needs an extra nlogn time.

Shudipta Sharma
  • 5,178
  • 3
  • 19
  • 33
0

Assuming that the numbers are in serial order

Two solutions

  1. Check while reading.
  2. Binary search for the missing number.
0

If the array is sorted then the element can be found in O(log n) time and O(1) space

Using Binary Search.

int search(int *ar, int n) { 
    int a = 0, b = n - 1; 
    int mid; 
    while ((b - a) > 1) { 
        mid = a + ((b-a) >> 1); 
        if ((ar[a] - a) != (ar[mid] - mid)) 
            b = mid; 
        else if ((ar[b] - b) != (ar[mid] - mid)) 
            a = mid; 
    } 
    return (ar[mid] + 1); 
} 

If the array is not sorted

n*(n+1)/2 - sum(array)

where n is the length of the array.
Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21