Skip to content
Advertisement

What is the time complexity of HashMap insertion and retrieval inside of a for loop?

I have written this code for an application but I’m having difficulty figuring out if its better than the legacy code (legacy code used one hashmap with List in every value). From what I understand, since Java 8 the insertion and retrieval from a Hashmap is O(log n) and the for loop is O(n) in my case. Am I correct in assuming that the time complexity here would be O(n log n)?

//complexity => O(n)
  for (int i = 0; i < len; i++) {
        String s = someList.get(i);
        int someValue = someArray[i];
        if (someCondition < 0) {
            // complexity => O(log n)
            if (hashmap1.containsKey(s)) {
                //complexity => O(log n) + O(log n) = O(log n)
                hashmap1.put(s, hashmap1.get(s) + someValue);
                //complexity => O(log n) + O(log n) = O(log n)
                hashmap2.put(s, hashmap2.get(s) + 1);
            } else {
                //complexity => O(log n)
                hashmap1.put(s, someValue);
                //complexity => O(log n)
                hashmap2.put(s, 1);
            }
        }
    }

Advertisement

Answer

It’s O(n) for traversing the for loop for the elements and O(1) for the HashMap, the final answer is O(n), see more in here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement