Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of treeset's subset method?

I am looking for time complexity of subset method of treeset. Is it O(n) where n is the number of items in the navigation set ?

like image 879
JavaDeveloper Avatar asked Mar 16 '15 00:03

JavaDeveloper


People also ask

What is the time complexity of TreeSet?

Likewise, the TreeSet has O(log(n)) time complexity for the operations listed in the previous group. This is because of the TreeMap implementation. The time complexity for ConcurrentSkipListSet is also O(log(n)) time, as it's based in skip list data structure.

Are Treesets sorted?

Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.

How do you make a subSet from TreeSet?

subSet() is used to return a subset of the existing TreeSet within a range mentioned in the parameter. The method takes in an upper limit and a lower limit and returns all the elements mentioned in the range. The lower limit is included if the element is present within the set and the upper limit is excluded.

Does TreeMap and TreeSet use HashMap internally?

TreeSet is practically implemented using TreeMap instance, similar to HashSet which is internally backed by HashMap instance.


1 Answers

The subSet() method of TreeSet internally calls subMap() method of TreeMap. TreeMap in Java is implemented using Red-Black tree. The subMap() method return new object of SubMap class, which is an internal class(nested class) in TreeMap. The constructor of SubMap class only store the first and last key of the subMap as implemented below:

SubMap(Object minKey, Object maxKey)
{
  if (minKey != nil && maxKey != nil && compare(minKey, maxKey) > 0)
    throw new IllegalArgumentException("fromKey > toKey");
  this.minKey = minKey;
  this.maxKey = maxKey;
}

Most operation takes same time as TreeMap, except the size() method. The size() method of SubMap class is implemented as below:

public int size()
{
  //Returns node >= minKey(i.e. first node in subSet). Takes O(logN) time.
  Node node = lowestGreaterThan(minKey, true);
  //Returns node >= maxKey(i.e. first node in subSet). Takes O(logN) time.
  Node max = lowestGreaterThan(maxKey, false);
  int count = 0;
  while (node != max)
    {
      count++;
      //In worst case, successor takes logN time
      node = successor(node);
    }
  return count;
}

The lowestGreaterThan() method takes O(logN) to find the key in subset. The successor() method takes O(logN), which is proportional to height in Red-Black tree, to find next successor. And to find the size of NavigableSet return by subSet, we need to traverse through each node in the subSet. Hence, the total complexity of function SubMap.size():- O(logN)+O(logN)+O(MlogN) ~ O(MlogN), where M is size of subset.

like image 175
Akshay Mishra Avatar answered Oct 22 '22 15:10

Akshay Mishra