DEV Community

Discussion on: Java Daily Coding Problem #001

Collapse
 
anduser96 profile image
Andrei Gatej

I’d use a set and iterate over the list and for each element I’d check if the set contains that element and if it does, it means we found a positive answer and if not, add k - arr[i] to the set.

for (int number: given){
   if (set.contains(number))
      return true;
    set.add(k - number);
}
 return false;

Thank you for sharing!

Collapse
 
ntt2k profile image
Trung Nguyen • Edited

I thought the same and this is way more efficient runtime.

Collapse
 
awwsmm profile image
Andrew (he/him)

Very clever! I like this answer.

Collapse
 
awwsmm profile image
Andrew (he/him)

What is the Big-O of this solution, though?

In the worst case, if we have...

2 elements: we will do a contains() on a set with 0 elements, then an add(), then a contains() on a set with 1 element, then an add().

3 elements: all of the above, plus a contains() on a set with 2 elements, then an add()

Assuming we skip the last add() when we know we've reached the end of the list, worst-case would be calling contains() on N sets of length 0 through N-1, plus calling add() N-1 times.

This is definitely less space-efficient than my solution, because of the set, but is it more time-efficient? What do you think?

Collapse
 
anduser96 profile image
Andrei Gatej

I think it depends on how set works under the hood.
At first, because there is only one for loop, one might think it’s only O(n).

But how does the `contains()’ method actually work? I have just read here and it says that set will internally iterate its elements and compare each element to the object passed as parameter.

Another way of making sure that there isn’t another for loop going on behind the scenes is by using a map. Because accessing an item requires O(1) time.(as far as I know)

Thread Thread
 
awwsmm profile image
Andrew (he/him)

So it could be that the Set solution is just as memory-efficient as the double-for loop. I'd love to do a benchmark of this.

Thread Thread
 
anduser96 profile image
Andrei Gatej

If you do, please let me know what the results are!
Thanks!

Collapse
 
rodiongork profile image
Rodion Gorkovenko

Ah, here is the answer already.

It's O(N) for sure. Sets (based on HashMaps) in Java have O(1) amortized for lookup and insert.

Collapse
 
techgirl1908 profile image
Angie Jones

yo!🔥