I have a boolean array:
bool * arr = new bool[n];
I want to figure out in constant time if there are any 1’s in this array; can this be done?
I know bitset has a none() method which does the same thing, but this array needs to be dynamically sized, and boost’s dynamic_bitset isn’t really an option.
Edited for clarity
Short answer: No. You have to examine half the elements on average, and that takes O(n) time.
Long answer: Yes. If you’re prepared to add some extra O(1) complexity to your write operations. Just keep track of every 0->1 and 1->0 with an up/down counter.
Note: I’m assuming that in the general case you have
bool *arr = new bool[n];. For a constant-sized array, then yes of course the query will be constant time!