This question is for real brainiacs, cause it should be done without an auxiliary array and has to be most efficient!
C program - needs to recieve an array with X numbers (suppose X=4 array : 5,4,3,2) and check if the array has all the numbers from 0 to X-1 (If X is 44 it needs to check if all numbers between 0 to 43 inside the array).
It has to be super efficient - I mean, running on the array 43 times is not an option!
Do you have any idea how to do this?? I'm trying to figure this one for hours without any success!!
It has to be O(n).
I don't understand what I'm missing in this question but AFAIK I don't see a reason why any (reasonable) solution should be anything more-/worse- than O(n)
time (and space) complexity.
From the above comments and answers, I understand the following:
check if all the array has all the numbers from 0 to X-1
. So anything less than 0
is not expected in the array. So I assume negative numbers are not allowedcheck if all the array has all the numbers from 0 to X-1
I guess if X
is the size of the array and all numbers from 0
to X-1
should be present, the I guess no duplicate numbers are allowed.So making the above assumptions, we can use one bit to check whether i
(0 <= i <= X-1
) is present or not. If i
is duplicate then it will fail mentioning that there is a duplicate number.
It scans the whole array one time - O(n)
and just uses one bit per element, so X
is 10
the X
bits are needed - for example consider we need to handle 1000000
elements and sizeof(int)
is 4
then we need 3.82M
of memory to hold the array elements and only 0.48M
is used for storing the presence of an element.
#include <stdio.h>
#define X 10
#define MIN 0
#define MAX X-1
int main(void)
{
//int arr[X] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
//int arr[X] = {6, 7, 8, 9, 0, 5, 3, 2, 11, 12};
//int arr[X] = {1, 1, 2, 4, 5, 6, 7, 8, 2, 2};
int arr[X] = {1, 3, 2, 4, 5, 6, -7, 8, 2, 2};
/* if X is more than sizeof(int) then change
the flag type to a wider one! */
int flag = 0;
int i;
for(i=0 ;i<X ; i++) {
if (arr[i] >= MIN && arr[i] <= MAX) {
if (flag & 1<<arr[i]) {
printf("Duplicate found : %d \n", arr[i]);
return -1;
}
flag |= 1<<arr[i];
} else {
printf("Failure at %d : %d \n", i, arr[i]);
return -1;
}
}
printf("Success \n");
return 0;
}