1

What is the BigO complexity of following lgorithms:

boolean intersection(TreeSet<?> set1, TreeSet<?> set1){
   if(set1.size() > set2.size()){
      return intersection(set2, set1);
   }
   for (Object e: set1){
       if(set2.contains(e)) return true;
   }
   return false;

}

UPDATE:

 N:=set1.size()
  K:=set2.size()

The possible answers: O(N*K) or O(N*log(K)) or O(K*log(N)) or O(N+K)

J.Olufsen
  • 13,415
  • 44
  • 120
  • 185

1 Answers1

1
O(N * log M)

N - size of set1, M - size of set2

Because we iterating on set1 elements (N) and for each iteration we call contains method which is logM complexity

TreeSet javadoc:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

mishadoff
  • 10,719
  • 2
  • 33
  • 55
  • i think the performance is not `O(N log K)` – Sage Nov 28 '13 at 14:39
  • @Sage I would not agree that tree iteration is `O(n * log n)`. All that iterator does it's inorder traversal. That's definitely O(n). – mishadoff Nov 28 '13 at 16:37
  • Well, how are we supposed to do in-order traversal on a tree? What kind of relation among the node must exist ? is there any supporting evidence or implementation that tells that we can actually traverse all of the element of a balanced-binary search tree in `O(n)` ? – Sage Nov 28 '13 at 16:51
  • There is parent for each node. So we actually move up in the tree. Take a look http://stackoverflow.com/questions/5471731/in-order-successor-in-binary-search-tree – mishadoff Nov 28 '13 at 17:40
  • Thank you. I can't believe that i have overlooked this premature theoretical knowledge. Actually the `successor(e)` call made me confused in the `next()` call as i have pointed out in my answer :(. – Sage Nov 28 '13 at 17:58