You don't need 2*10^9 bits of memory to solve this problem. The boundary on n (n < 10^5) suggest another solution:
(1) Sort the a_i
:
3 3 3 3 3 5 7 9
(2) Get rid of the duplicates by finding consecutive copies via binary search. In this case, you have 5
(=101
in binary), so 3 3 3 3 3
turns into 3 5
. Your a_i
are now 3 5 5 7 9
. (Note that this is equivalent to adding numbers in binary, but it's more efficient since you know that your numbers have up to 10^9 bits but at max 10^5 bits are set!)
(3) Repeat step 2 until you no longer have duplicates. In this example you only need another step, you end up with 3 6 7 9
.
(4) Calculate max(a_i) - number of a_i left + 1
. This is your result, in this case 9-4+1=6
.
Possible implementation of step (2) :
The first thing I would try is overwriting from the beginning, but keeping a pointer to check where I am at the moment, so: You read 3
. You binary search for the last 3
and keep a pointer to the following element. You then overwrite: 3 3 3 3 3 5 7 9
-> 3 5 x x x *5 7 9
(it doesn't matter what's at the x
positions, and the pointer is now at the 5
). Now, for a first solution, simply copy everything from the end to make it contiguous again: 3 5 5 7 9
and remember that your array is now shorter.
This is not the most efficient solution as it will lead to a lot of copying if you have an array like 3 3 4 4 5 5 6 6...
, but it should be decent enough.
For better performance, you could only do step (1) and then insert everything into a hashmap that maps a_i
to the number of times it appears, and then operate on that hashmap. That's pretty fast for your constraints, but implementing a hashmap in C isn't trivial.