[Solved] question on array and number


Interesting problem.

If the array is of signed integers, I believe it is possible in O(n) time and O(1) space, with no overflows, assuming the length is small enough to permit such a thing to happen.

The basic idea is as follows:

We have n numbers. Now on dividing those numbers by n+1, we get n remainders. So atleast one of the remainders in {0,1,2, …, n} must be missing (say r). We fill the array with numbers whose remainders are r.

First, we add a multiple of n+1 to all negative numbers to make them positive.

Next we walk the array and find the remainder of each number with n+1. If remainder is r, we set a[r] to be -a[r] if a[r] was positive. (If we encounter negative numbers when walking, we use the negated version when taking remainder).

We also have an extra int for remainder = n.

At the end, we walk the array again to see if there are any positive numbers (there will be one, or the extra int for remainder = n will be unset).

Once we have the remainder, it is easy to generate n numbers with that remainder. Of course we could always generate just one number and fill it with that, as the problem never said anything about unique numbers.

If the array was of unsigned integers, we could probably still do this with better book-keeping.


For instance we could try using the first n/logn integers as our bitarray to denote which remainders have been seen and use some extra O(1) integers to hold the numbers temporarily.

For eg, you do tmp = a[0], find remainder and set the appropriate bit of a[0] (after setting it to zero first). tmp = a[1], set bit etc. We will never overwrite a number before we need it to find its remainder.

3

solved question on array and number