I have variable x, and the functions f1(x), f2(x), …. fn(x) (n can be up to 1 million). The values of these functions are 1 or 0. So, how to write the algorithm,which can quickly pick up the functions which return 1? thanks.
Here I present mine. It has O(n) time complexity, which is not efficient enough.
List funHaveTrueValues = new ArrayList();
for (int i=1; i<=n; ++i){
if (fi(x)==true){
funHaveTrueValues.add(fi);
}
}
}
Could anybody propose O(1) algorithm? thanks!
If you can assume that each
fisO(1), then making at most 1.000.000 calls to them still has a constant upper bound. Thus I believe your sketched approach isO(1), if you limit it to 1.000.000 calls.Edit
As I got a few downvotes on this, I’ try to clarify the reasoning. Given the information at hand, there is no faster way to solve this than to evaluate all
f. If the question is really “Is there a faster/more clever way to do this?” then the answer is (as many have answered) no.If the question however is in the style of “I got this question on a complexity theory test” (or similar) then it might be a “gotcha!”. This is the case I aimed for with my answer. In the generalized problem (with
nfunctions, no limits) the time complexity isO(n)granted that each function behaves as anO(1)oracle. By introducing the roof of 1.000.000 functions, time complexity gets a constant upper bound ofO(1000000 * 1) = O(1).