0

I was looking at java source code in HashMap class.

final int hash(Object k) {
    int h = 0;
    if (useAltHashing) {
        if (k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
        h = hashSeed;
    }

    h ^= k.hashCode();

So, what is the time complexity of hashmapObject.put("somestring") ? Is it O(1) or O(n) where n is number of characters in a string.

2
  • 2
    Adding something to a HashMap is guaranteed to be O(1) (assuming perfect hash distribution). Your hash function might be O(whatever) though... And your equals... Commented Dec 13, 2014 at 22:48
  • Check this topic out Commented Dec 13, 2014 at 23:10

2 Answers 2

2

It is O(1) w.r.t. the size of the map, which is what is usually of interest. It is O(N) w.r.t. the length of the string.

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

Comments

2

In worst case time(In practise it happens rarely , only when we have a bad hashing function) complexity for put method in hashmap is O(N), because although we add the element at the beginning of the linked list(O(1)) but we still need to loop through the bucket(linked list) to determine if that new element already exists or not.
Updated: As per Peter Lawery comment in java 8 its O(log n). This optimization is described here but in a nutshell an ad-hoc implementation of tree map is used as a bucket when the size of the bucket crosses the threshold value. The threshold value is setted by the variable static final int TREEIFY_THRESHOLD = 8; in HashMap.java

12 Comments

Hash map (or hash table) is an associative array. It can be implemented with a linked list, but I don't believe the Java one is. I didn't down vote by the way.
That being said, your answer isn't wrong. Just can be more accurate. You are correct in saying the put function has a worse case scenario of O(n)
@CyberneticTwerkGuruOrc The bucket in java is linkedList(not java.util.LinkedList but simpler version). There is also a variable table which is indeed an array that contains object of type linkedList
@CyberneticTwerkGuruOrc Java HashMap uses a version of a linked list for allowing multiple items in the same bucket.
Worst case complexity only happens if the hash function is degenerate - worth mentioning that.
|

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.