Is it possible to go through a boolean array to find a false value in O(logn) running time? The array's indices run from 0 to n-1.
If it is, how would we do it in java? Pseudo code is fine.
Is it possible to go through a boolean array to find a false value in O(logn) running time? The array's indices run from 0 to n-1.
If it is, how would we do it in java? Pseudo code is fine.
No. This is not possible without any further information about the array.
The best you can do is O(n)
, which is traversing the array from left to right and checking each item.
If the array is sorted you would need two checks, a false value could be on either end, which is O(1)
.
A common proof by contradiction:
Assume that the algorithm works correctly. Then, after inspecting less than all elements, the algorithm yields a correct answer. Now assume the algorithm has seen only true
s, it yields an answer x. By now only changing values the algorithm has not inspected, I can always construct a test case in which the algorithm fails. Therefore, the algorithm must inspect all elements of an (unsorted) boolean array to determine if all are true.
In general, the answer is "NO": you cannot go through an array in search of a single value in less than O(N)
, unless you know something about the order of array items.
For example, if the array is sorted, you can find the right spot in O(log N)
.
For boolean
array being sorted means having all false
s, if any, at the beginning, and all true
s, if any, at the the end. If this is the case, you can use binary search to find the "demarcation point" in logarithmic time.
Whatever you do, you will have to check all the values to ensure there is no false value. So linear time, with n/2 checks in average.