-2

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);
            }
        }
    }
Fclass
  • 69
  • 6
  • 2
    HashMaps generally have O(1) insertion and lookup complexity unless your map degenerated and put everything into one / few buckets. Your loop body is O(1) and therefore the entire thing is O(n). `someList.get(i)` however could be a problem depending on the list implementation, because that may actually not be a constant access. – luk2302 Mar 04 '22 at 08:26
  • Only TreeMap has complexity of O(log n) on insertion and retrieval not Hashmap – HariHaravelan Mar 04 '22 at 08:29
  • I'm not too worried about the `someList.get(i)` part because it's a very small list with just 12 entries. Thanks for the reply, I really appreciate it. – Fclass Mar 04 '22 at 08:33
  • @Fclass please consider to accept the answers to improve the community . – Lunatic Mar 04 '22 at 08:34
  • It doesn't affect the complexity, but the `containsKey` if/else can be replaced by `hashmap1.merge(s, someValue, Integer::sum); hashmap2.merge(s, 1, Integer::sum);`. – Andy Turner Mar 04 '22 at 09:08

1 Answers1

2

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.

Lunatic
  • 1,519
  • 8
  • 24