简体   繁体   中英

Time complexity of this algorithm in Big(O)

I came up with the following algorithm to calculate the time complexity to find the second most occuring character in a string. This algo is divided into two parts. The first part where characters are inserted into a map in O(n). I am having difficulty with the second part. Iterating over the map is O(n) push and pop is O(log(n)). what would be the BigO complexity of the second part? finally what would the overall complexity be? Any help understanding this would be great?

void findKthHighestChar(int k,std::string str)
{
    std::unordered_map<char, int> map;
    
    //Step 1: O(n)
    for (int i = 0; i < str.size(); i++)
    {
        map[str[i]] = map[str[i]] + 1;
    }

    //Step2: O(n*log())
    //Iterate through the map
    using mypair = std::pair<int, char>;
    std::priority_queue<mypair, std::vector<mypair>, std::greater<mypair>> pq;
    for (auto it = map.begin(); it != map.end(); it++) //This is O(n) .
    {
        pq.push(mypair(it->second, it->first)); //push is O(log(n))

        if (pq.size() > k) {
            pq.pop();                           //pop() is O(log(n))
        }
    }
    std::cout << k << " highest is " << pq.top().second;
}

You have 2 input variables, k and n (with k < n ).
And one hidden: alphabet size A

  • Step1 has average-case complexity of O(n) .

  • Step2: O(std::min(A, n)*log(k)) .

    Iterating the map is O(std::min(A, n))

    Queue size is bound to k , so its operation are in O(log(k))

Whole algorithm is so O(n) + O(std::min(A, n)*log(k)) If we simplify and get rid of some variables to keep only n :

  • ( k -> n , A -> n ): O(n) + O(n*log(n)) so O(n*log(n)) .
  • ( k -> n , std::min(A, n) -> A ) : O(n) + O(log(n)) so O(n) .

Does it have to be this algorithm?

You can use an array (of the size of your alphabet) to hold the frequencies.

You can populate it in O(n), (one pass through your string). Then you can find the largest, or second largest, frequency in one pass. Still O(n).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM