0

I have a list of sorted intervals and another list, which describes the index of every interval. Here's an example:

intervals = [(0, 2), (2, 3), (4, 6)] // (0, 2) includes 0, but doesn't include 2

values = [2, 3, 7]

Now, I want to know, how often every interval is "mentioned". An interval is mentioned, when it's value is in another interval. The problem is, that when an interval is mentioned n-times, all the intervals it mentions are also mentioned n-times. All intervals are by default mentioned one time. So, (4, 6) is mentioned one time, (2, 3) one time too, but (0, 2) is mentioned two times, because it's index 2 is in the interval (2, 3). I would like to get the list [2, 1, 1] as an output in this example. Note that the values in the list are always increasing and that an interval can only mention intervals above itself.

I already have a solution, but its time complexity is O(n**2) and that's too slow for me. Does anybody now a linear or a O(n*log n) solution?

Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57
  • *not increasing but decreasing – entenfaenger Jan 03 '21 at 16:10
  • 1
    why is the result 1 for value 7? 7 doesn't fall in any interval. – Shridhar R Kulkarni Jan 03 '21 at 17:43
  • @ShridharRKulkarni "All intervals are by default mentioned one time." – IVlad Jan 03 '21 at 22:13
  • 1
    I'd look into interval trees. They are `O(N log N)` for this, but they are also output sensitive, so if you have a lot of overlap (there are many values which each mention many intervals) they can approach `O(N^2).` In this example though, the only output it would have would be the 2 in (2,3). https://en.wikipedia.org/wiki/Interval_tree – Nuclearman Jan 04 '21 at 02:34
  • @ThomasRiedle Could you please give one more example? What is `n`? – Shridhar R Kulkarni Jan 04 '21 at 02:50
  • Segment trees would be more suitable as the queries are point queries. – Shridhar R Kulkarni Jan 04 '21 at 04:25
  • Another example would be: intervals = [(0, 2), (1, 4), (6, 7), (9, 10)] values = [2, 6, 7, 10]. In this example, the output should be: [3, 2, 1, 1]. n is the amount of given intervals, in this example four. Unfortunately, the intervals are overlapping a lot, so I don't know wether interval trees would work... – entenfaenger Jan 04 '21 at 08:18

0 Answers0