Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of std::count

I was in some online code quiz website where there is a complexity restriction that the code should not exceed O(N) in both time and memory where N is the size of the vector A. My code was exactly (Full Code):

int foo(int X, const std::vector<int> &A) {
    auto N = A.size();
    auto total_hit = std::count(A.cbegin(), A.cend(), X);
    auto K = N - total_hit;
    if (K < 0 || K >= N){
        return -1;
    }
    return K;
}

I got a result that I exceed the time complexity. Is there any possibility rather than they are wrong?

like image 304
Humam Helfawi Avatar asked May 27 '16 21:05

Humam Helfawi


1 Answers

According to the ref:

Complexity: exactly last - first comparisons / applications of the predicate

they are wrong!

And cplusplus agrees:

Complexity: Linear in the distance between first and last: Compares once each element.


Of course, the complexity of std::cbegin(), std::cend() and std::vector::size() is constant.


If I were you, I would contact the site, linking them to this question.

like image 118
gsamaras Avatar answered Nov 12 '22 22:11

gsamaras