0

How can I find how many elements are missing from an array of integers in C, if some of the numbers are duplicated?

Assume the array is int array = {1, 2, 1, 5, 4} and there should be numbers up to 6. Then, the program/function should output/return 2, as there are 2 elements missing (3, 6).

Note: 0 is not counted as a missing number, nor can it be present in an array.

asked Nov 1, 2015 at 1:13
2
  • 2
    Are you saying an array of length n can have numbers between 1 to n+1? Commented Nov 1, 2015 at 1:19
  • @YoungHobbit No, the array elements could've been the same, but for example numbers up to 10 could have been missing. Therefore, there would be 6 elements missing. The maximum number of the sequence (6 in the question) can be anything. (But it is obviously specified beforehand) Commented Nov 1, 2015 at 1:25

1 Answer 1

2

This way?

int countMissing(int *x, int arrLen, int bound)
{
 int * y = malloc ((bound + 1) * sizeof(int));
 int i = 0;
 int missing = 0;
 memset(y,0,sizeof(int)*(bound+1));
 for(i = 0; i<arrLen; i++)
 {
 if(x[i]<=bound)
 {
 y[x[i]] = 1;
 }else
 {
 // error handling e.g.
 return -1;
 }
 }
 for(i = 1; i<=bound; i++)
 {
 if(y[i]==0) missing++;
 }
 free(y);
 return missing;
}

Usage:

int main(void) 
{
 int array [] = {1, 2, 1, 5, 4};
 printf("%d", countMissing(array, 5, 10));
 return 0;
}

Output: 6.

answered Nov 1, 2015 at 1:23
12
  • Nits: (1) you should allocate char *y to save some space; (2) you should use y[x[i]-1] or allocate an array of size bound+1, because otherwise you have an out-of-bounds access; (3) you should free your array. Commented Nov 1, 2015 at 1:29
  • @nneonneo: fixing, I don't have a debugger with me; should work now Commented Nov 1, 2015 at 1:36
  • 1
    Why are you using memset() instead of calloc()? Commented Nov 1, 2015 at 1:43
  • @Mitsos101: That is a style thing Commented Nov 1, 2015 at 1:44
  • @Giorgi Does the memory need to be zeroed out anyway though? Commented Nov 1, 2015 at 1:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.