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 than0is 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-1I guess ifXis the size of the array and all numbers from0toX-1should 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. Ifiis 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, soXis10theXbits are needed – for example consider we need to handle1000000elements andsizeof(int)is4then we need3.82Mof memory to hold the array elements and only0.48Mis used for storing the presence of an element.