educative.io

Difference between time complexity of collections.counter vs hashmap

I used hashmap method as suggested in the solutions but also tried Collections.counter instead of the hashmap and ran both on leetcode.
Could someone explain why the space complexity of Collections.counter better than hashmaps and what is the runtime complexity of Collections.counter

Hello @Shivam_Nanda,

Hashmap works on the principle of hashing and internally uses hashcode as a base to store key-value pairs. With the help of hashcode, Hashmap distributes the objects across the buckets so that hashmap puts the objects and retrieves them in constant time O(1).

On the other hand, Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class that’s why it has better space complexity than hashmaps.

Thank you