Given you have an array A[1..n] of size n, it contains elements from the set {1..n}. However, two of the elements are missing, (and perhaps two of the array elements are rep
Cycle each element 0...n-1.
x = abs(A[i]) (with i = 0...n-1);
A[x - 1] can be:
> 0: we haven't checked the element, change its sign to negative:
A[x - 1] = -A[x - 1]
< 0: we already found the same number
At the end of the cycle, pass each A[0...n-1]. The index of the positive elements + 1 is the missing numbers.
So if
y = abs(A[i]) > 0: i + 1 is missing.
In C#
var arr = new[] { 1, 2, 1, 2, 4 };
for (int i = 0; i < arr.Length; i++) {
int x = Math.Abs(arr[i]);
int y = arr[x - 1];
if (y > 0) {
arr[x - 1] = -arr[x - 1];
}
}
for (int i = 0; i < arr.Length; i++) {
int x = arr[i];
if (x > 0) {
Console.WriteLine("Missing {0}", i + 1);
} else {
arr[i] = -arr[i];
}
}
And the array is as good as new.
As you have given an array of n size and find the missing number when it's in a sequence.
#include<stdio.h>
main()
{
print("value of n");
scan("%d",&n);
print("enter the elements");
for(i=0;i<n;i++)
scan("%d",&a[i]);
for(i=0;i<n;i++)
{
d1[i]=a[i+1]-a[i];
temp=d1[i];
d[i]=temp;
}
for(i=0;i<n;i++)
{
if(d[i]==d[i+1]
{
c=d[i];
break;
}
}
for(i=0;i<n;i++)
b[i]=a[0]+i*c;
for(i=0;i<n;i++)
{
miss=0;
for(j=0;j<n;j++)
{
if(b[i]!=a[j])
{
miss++;
}
if(miss==n)
print("missing no. %d",b[i]);
}
}
It would find the missing when its in sequence only.
This is bit qwirky As all your numbers are positive (by problem). I ll make the number at position i-1 a negetive if i is present in array.
int i;
for(i = 0; i < n; i++) {
A[abs(A[i])-1] = -1*abs(A[abs(A[i])-1]);
}
for(i = 0; i < n; i++) {
if(A[i]>0) {
printf("missing: %d", i+1);
}
Complexity O(n), no auxiliary array user, but destroys the input array.