Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);
            }
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading