1

Algorithm:

  1. insert element counts in a map
  2. start from first element
  3. if first is present in a map, insert in output array (total number of count), increment first
  4. if first is not in a map, find next number which is present in a map

Complexity: O(max element in array) which is linear, so, O(n).

vector<int> sort(vector<int>& can) {
    unordered_map<int,int> mp;
    int first = INT_MAX;
    int last = INT_MIN;
    for(auto &n : can) {
        first = min(first, n);
        last = max(last, n);
        mp[n]++;
    }
    vector<int> out;
    while(first <= last) {
        while(mp.find(first) == mp.end()) first ++;
        int cnt = mp[first];
        while(cnt--) out.push_back(first);
        first++;
    }
    return out;
}
3
  • It’s counting sort and is O(n) Commented Feb 22, 2020 at 2:50
  • 2
    @SomeDude It's O(n + k) where k = (last - first), not O(n) - the Wikipedia page you linked to says this, too. Commented Feb 22, 2020 at 2:57
  • @kaya3 yes I agree Commented Feb 22, 2020 at 3:23

1 Answer 1

2

Complexity: O(max element in array) which is linear, so, O(n).

No, it's not O(n). The while loop iterates last - first + 1 times, and this quantity depends on the array's contents, not the array's length.

Usually we use n to mean the length of the array that the algorithm works on. To describe the range (i.e. the difference between the largest and smallest values in the array), we could introduce a different variable r, and then the time complexity is O(n + r), because the first loop populating the map iterates O(n) times, the second loop populating the vector iterates O(r) times, and its inner loop which counts down from cnt iterates O(n) times in total.

Another more formal way to define n is the "size of the input", typically measured in the number of bits that it takes to encode the algorithm's input. Suppose the input is an array of length 2, containing just the numbers 0 and M for some number M. In this case, if the number of bits used to encode the input is n, then the number M can be on the order of O(2n), and the second loop does that many iterations; so by this formal definition the time complexity is exponential.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.