2

Suppose, I have such a data structure

NavigableMap<Long, NavigableMap<Long, Set<String> map = new TreeMap<>();

And I want to calculate the complexity for the algorithm below:

SortedSet<Widget> result = new TreeSet<>();
map.tailMap(first, true)
    .forEach( (k, v)-> {
        v.headMap(second, true)
                .forEach((key, value) -> result.addAll(value));
    });

This is correct, that complexity will be equal to

O(log (n + k) * (log (k + m) + log (m))) ?

Where

  • n - count of elements in original map
  • k - count of elements in tailMap(first, true)
  • m - count of elements in headMap(second, true)
  • First of all I've noticed that there's something wrong with the types. It seems you're trying to `addAll` `Set` to `SortedSet`. Fix it please to make your question better. – Vladimir Pligin Nov 28 '19 at 08:26
  • You have two nested loops, the outer one one has *k* iterations, the inner one has *m* iterations (for each of the *k* iterations, with a different *m* every time, depending on the number of elements in these second-level maps). So should be `O(k*m)`. If you want to bound *k* and *m* to some *N* (maximum number of elements in all these maps), you get `O(N^2)`. But if there are some restrictions on `first` and `second` this could be lower. – Thilo Nov 28 '19 at 08:26
  • @Thilo thanks for your reply. But I thought that ```tailMap(first, true) .forEach ``` expression is equal to ```O(log (n + k))```. I was guided by this answer - https://stackoverflow.com/a/38868745/11698998. Is this answer wrong? – Artem Smirnov Nov 28 '19 at 09:09
  • That answer says `O(log(n) + k)` which is much different from `O(log (n + k))`. – Thilo Nov 28 '19 at 09:25
  • @Thilo thanks again! It was my mistake. It turns the complexity is even higher and equal to ```O(log (n) + k) * (log (k) + m)) ```? – Artem Smirnov Nov 28 '19 at 10:37
  • 4
    Unless you have a reason to assume that the sizes of the submaps will not scale with the total size map, there is no need to distinguish between them for the Big O notation. So given size *n* and *m* for outer and inner map sizes, the time complexity is just `O(n + log n) * O(m + log m) `, as the worst case always is that the submap is as large as the entire map and as said, unless there’s a reason to assume that the average is different than somewhere between best and worst case for your scenario, there’s no point in formulating a different time complexity for it. – Holger Nov 28 '19 at 12:19
  • And `O(n + log n)` is the same as `O(n)`, so you end up with `O(n * m )` – Thilo Nov 28 '19 at 12:52

0 Answers0