2

Let say I have a list of ranges like this

[[1,3], [2,5], [4,6], [8,10], [12,15], [13,17]]

Now I want to find a range say [3,11] falls in. My algorithm should give me all the ranges this range falls to. For example the output for this should be

Output - [1,3], [2,5], [4,6], [8,10]

How do i go about solving this?

PS: I know segment tree might be helpful. Where I can build the tree to store interval and query a Point lying inside interval, but how to get all intervals given a interval.

Davis Molinari
  • 741
  • 1
  • 5
  • 20
Muthu Rg
  • 632
  • 1
  • 6
  • 18
  • 2
    From https://en.wikipedia.org/wiki/Interval_tree we have "Specifically, it allows one to efficiently find all intervals that overlap with any given interval or point" – mcdowella Apr 12 '17 at 04:37
  • If this is a one-off task given a list of ranges, you simply brute-force through the list. If you need to query often on the same data, you build a tree. If the data changes often but you query rarely, you might find another structure more useful. – le_m Apr 12 '17 at 15:48

1 Answers1

1

Interval Tree is definitely the data structure you need. I faced the same problem and in order to improve performances I used Augmented Interval Tree where every node includes, in addition to the bounds of the range, also the information related to the maximum value of the subtree of the node.

You can find here an in depth explanation and a Java implementation: Data Structures: Augmented Interval Tree to search for intervals overlapping

Davis Molinari
  • 741
  • 1
  • 5
  • 20