'GEEK FOR GEEKS missing number in array problem

I was solving missing number in an array problem. the editorial showed it is solved by

  1. first get sum on n number.
  2. minus each element from given array the result will be the missing number.

but I solved it by another method. 1. I declared another array of n+1 size. 2. For each element in given array. eg n=5 a[1,2,3,5] where 4 is missing. I declare array[ignore,1,1,1,garbage,1] {here index 0 is ignored. notice given array has element 1 2 3 and 5, So i save 1 on index 1,2,3 and5 } now traverse the array from i=1 and the index which has value not equal to 1 is the missing number.

here is my code.

**

int missing(int arr[], int n)
{
    int a[n + 1];
    for (int i = 0; i < n - 1; i++)
    {
        a[arr[i]] = 1;
    }
    for (int i = 1; i < n + 1; i++)
    {
        if (a[i] != 1)
        {
            return i;
        }
    }
}

**

but for n=706 in which 621 is missing. geek for geek code editor shows case fialed while my personal editor show result 621 which is right.

notice the problem constraints 1<=N<=10^6

thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source