Open In App

Interval Tree

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Consider a situation where we have a set of intervals and we need following operations to be implemented efficiently. 
1) Add an interval 
2) Remove an interval 
3) Given an interval x, find if x overlaps with any of the existing intervals.
Interval Tree: The idea is to augment a self-balancing Binary Search Tree (BST) like Red Black Tree, AVL Tree, etc to maintain set of intervals so that all operations can be done in O(Logn) time. 
Every node of Interval Tree stores following information. 
a) i: An interval which is represented as a pair [low, high] 
b) max: Maximum high value in subtree rooted with this node.
The low value of an interval is used as key to maintain order in BST. The insert and delete operations are same as insert and delete in self-balancing BST used. 
 

IntervalSearcTree

The main operation is to search for an overlapping interval. Following is algorithm for searching an overlapping interval x in an Interval tree rooted with root

Interval overlappingIntervalSearch(root, x)
1) If x overlaps with root's interval, return the root's interval.

2) If left child of root is not empty and the max  in left child 
is greater than x's low value, recur for left child

3) Else recur for right child.

How does the above algorithm work? 
Let the interval to be searched be x. We need to prove this in for following two cases.
Case 1: When we go to right subtree, one of the following must be true. 
a) There is an overlap in right subtree: This is fine as we need to return one overlapping interval. 
b) There is no overlap in either subtree: We go to right subtree only when either left is NULL or maximum value in left is smaller than x.low. So the interval cannot be present in left subtree.
Case 2: When we go to left subtree, one of the following must be true. 
a) There is an overlap in left subtree: This is fine as we need to return one overlapping interval. 
b) There is no overlap in either subtree: This is the most important part. We need to consider following facts. 
… We went to left subtree because x.low <= max in left subtree 
…. max in left subtree is a high of one of the intervals let us say [a, max] in left subtree. 
…. Since x doesn’t overlap with any node in left subtree x.high must be smaller than ‘a‘. 
…. All nodes in BST are ordered by low value, so all nodes in right subtree must have low value greater than ‘a‘. 
…. From above two facts, we can say all intervals in right subtree have low value greater than x.high. So x cannot overlap with any interval in right subtree.
Implementation of Interval Tree: 
Following is C++ implementation of Interval Tree. The implementation uses basic insert operation of BST to keep things simple. Ideally it should be insertion in AVL Tree or insertion in Red-Black Tree. Deletion from BST is left as an exercise.
 

CPP




#include <iostream>
using namespace std;
 
// Structure to represent an interval
struct Interval
{
    int low, high;
};
 
// Structure to represent a node in Interval Search Tree
struct ITNode
{
    Interval *i;  // 'i' could also be a normal variable
    int max;
    ITNode *left, *right;
};
 
// A utility function to create a new Interval Search Tree Node
ITNode * newNode(Interval i)
{
    ITNode *temp = new ITNode;
    temp->i = new Interval(i);
    temp->max = i.high;
    temp->left = temp->right = NULL;
    return temp;
};
 
// A utility function to insert a new Interval Search Tree Node
// This is similar to BST Insert.  Here the low value of interval
// is used tomaintain BST property
ITNode *insert(ITNode *root, Interval i)
{
    // Base case: Tree is empty, new node becomes root
    if (root == NULL)
        return newNode(i);
 
    // Get low value of interval at root
    int l = root->i->low;
 
    // If root's low value is smaller, then new interval goes to
    // left subtree
    if (i.low < l)
        root->left = insert(root->left, i);
 
    // Else, new node goes to right subtree.
    else
        root->right = insert(root->right, i);
 
    // Update the max value of this ancestor if needed
    if (root->max < i.high)
        root->max = i.high;
 
    return root;
}
 
// A utility function to check if given two intervals overlap
bool doOVerlap(Interval i1, Interval i2)
{
    if (i1.low <= i2.high && i2.low <= i1.high)
        return true;
    return false;
}
 
// The main function that searches a given interval i in a given
// Interval Tree.
Interval *overlapSearch(ITNode *root, Interval i)
{
    // Base Case, tree is empty
    if (root == NULL) return NULL;
 
    // If given interval overlaps with root
    if (doOVerlap(*(root->i), i))
        return root->i;
 
    // If left child of root is present and max of left child is
    // greater than or equal to given interval, then i may
    // overlap with an interval is left subtree
    if (root->left != NULL && root->left->max >= i.low)
        return overlapSearch(root->left, i);
 
    // Else interval can only overlap with right subtree
    return overlapSearch(root->right, i);
}
 
void inorder(ITNode *root)
{
    if (root == NULL) return;
 
    inorder(root->left);
 
    cout << "[" << root->i->low << ", " << root->i->high << "]"
         << " max = " << root->max << endl;
 
    inorder(root->right);
}
 
// Driver program to test above functions
int main()
{
    // Let us create interval tree shown in above figure
    Interval ints[] = {{15, 20}, {10, 30}, {17, 19},
        {5, 20}, {12, 15}, {30, 40}
    };
    int n = sizeof(ints)/sizeof(ints[0]);
    ITNode *root = NULL;
    for (int i = 0; i < n; i++)
        root = insert(root, ints[i]);
 
    cout << "Inorder traversal of constructed Interval Tree is\n";
    inorder(root);
 
    Interval x = {6, 7};
 
    cout << "\nSearching for interval [" << x.low << "," << x.high << "]";
    Interval *res = overlapSearch(root, x);
    if (res == NULL)
        cout << "\nNo Overlapping Interval";
    else
        cout << "\nOverlaps with [" << res->low << ", " << res->high << "]";
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    static class Interval {
        int low, high;
 
        public Interval(int low, int high)
        {
            this.low = low;
            this.high = high;
        }
 
        public String toString()
        {
            return "[" + this.low + "," + this.high + "]";
        }
    }
 
    static class Node {
        Interval range;
        Node left, right;
        int max;
 
        public Node(Interval range, int max)
        {
            this.range = range;
            this.max = max;
        }
 
        public String toString()
        {
            return "[" + this.range.low + ", "
                + this.range.high + "] "
                + "max = " + this.max + "\n";
        }
    }
 
    public static Node insert(Node root, Interval x)
    {
        if (root == null) {
            return new Node(x, x.high);
        }
        if (x.low < root.range.low) {
            root.left = insert(root.left, x);
        }
        else {
            root.right = insert(root.right, x);
        }
        if (root.max < x.high) {
            root.max = x.high;
        }
        return root;
    }
 
    public static void inOrder(Node root)
    {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root);
        inOrder(root.right);
    }
 
    public static Interval isOverlapping(Node root,
                                         Interval x)
    {
        if (root == null) {
            // return a dummy interval range
            return new Interval(-1, -1);
        }
        // if x overlaps with root's interval
        if ((x.low > root.range.low
             && x.low < root.range.high)
            || (x.high > root.range.low
                && x.high < root.range.high)) {
            return root.range;
        }
        else if (root.left != null
                 && root.left.max > x.low) {
            // the overlapping node may be present in left
            // child
            return isOverlapping(root.left, x);
        }
        else {
            return isOverlapping(root.right, x);
        }
    }
 
    public static void main(String[] args)
    {
        Node root = insert(null, new Interval(15, 20));
        root = insert(root, new Interval(10, 30));
        root = insert(root, new Interval(17, 19));
        root = insert(root, new Interval(5, 20));
        root = insert(root, new Interval(12, 15));
        root = insert(root, new Interval(30, 40));
 
        System.out.println(
            "Inorder traversal of constructed Interval Tree is");
        inOrder(root);
        System.out.println();
        Interval i = new Interval(6, 7);
        System.out.println("Searching for interval " + i);
        System.out.println(
            "Overlaps with "
            + isOverlapping(root, new Interval(6, 7)));
    }
    // contributed by rishabhtiwari759
}


Python3




# Python Code for Interval tree
class Interval:
    def __init__(self, low, high):
        self.low = low
        self.high = high
 
    def __str__(self):
        return "[" + str(self.low) + "," + str(self.high) + "]"
 
 
class Node:
    def __init__(self, range, max):
        self.range = range
        self.max = max
        self.left = None
        self.right = None
 
    def __str__(self):
        return "[" + str(self.range.low) + ", " + str(self.range.high) + "] " + "max = " + str(self.max) + "\n"
 
 
def insert(root, x):
    if root == None:
        return Node(x, x.high)
 
    if x.low < root.range.low:
        root.left = insert(root.left, x)
    else:
        root.right = insert(root.right, x)
 
    if root.max < x.high:
        root.max = x.high
 
    return root
 
 
def inOrder(root):
    if root == None:
        return
 
    inOrder(root.left)
    print(root, end="")
    inOrder(root.right)
 
 
def isOverlapping(root, x):
    if root == None:
        # return a dummy interval range
        return Interval(-1, -1)
 
    # if x overlaps with root's interval
    if (x.low > root.range.low and x.low < root.range.high or (x.high > root.range.low and x.high < root.range.high)):
        return root.range
 
    elif (root.left != None and root.left.max > x.low):
        # the overlapping node may be present in left child
        return isOverlapping(root.left, x)
 
    else:
        return isOverlapping(root.right, x)
 
 
if __name__ == '__main__':
    root = None
    root = insert(None, Interval(15, 20))
    root = insert(root, Interval(10, 30))
    root = insert(root, Interval(17, 19))
    root = insert(root, Interval(5, 20))
    root = insert(root, Interval(12, 15))
    root = insert(root, Interval(30, 40))
 
    print("Inorder traversal of constructed Interval Tree is")
    inOrder(root)
    print()
    i = Interval(6, 7)
    print("Searching for interval", i)
    print("Overlaps with ", isOverlapping(root, i))
 
# This code is contributed by Tapesh (tapeshdua420)


C#




// C# Code for Interval Tree
using System;
 
class Program {
    static void Main(string[] args)
    {
 
        Node root = insert(null, new Interval(15, 20));
        root = insert(root, new Interval(10, 30));
        root = insert(root, new Interval(17, 19));
        root = insert(root, new Interval(5, 20));
        root = insert(root, new Interval(12, 15));
        root = insert(root, new Interval(30, 40));
 
        Console.WriteLine(
            "Inorder traversal of constructed Interval Tree is");
 
        inOrder(root);
 
        Console.WriteLine();
 
        Interval i = new Interval(6, 7);
 
        Console.WriteLine("Searching for interval " + i);
 
        Console.WriteLine(
            "Overlaps with "
            + isOverlapping(root, new Interval(6, 7)));
    }
 
    public class Node {
 
        public Interval range;
        public Node left, right;
        public int max;
 
        public Node(Interval range, int max)
        {
            this.range = range;
            this.max = max;
        }
 
        public override string ToString()
        {
            return "[" + this.range.low + ", "
                + this.range.high + "] "
                + "max = " + this.max + "\n";
        }
    }
    public class Interval {
 
        public int low, high;
 
        public Interval(int low, int high)
        {
            this.low = low;
            this.high = high;
        }
 
        public override string ToString()
        {
            return "[" + this.low + "," + this.high + "]";
        }
    }
 
    public static Node insert(Node root, Interval x)
    {
        if (root == null) {
            return new Node(x, x.high);
        }
        if (x.low < root.range.low) {
            root.left = insert(root.left, x);
        }
        else {
            root.right = insert(root.right, x);
        }
        if (root.max < x.high) {
            root.max = x.high;
        }
        return root;
    }
    public static void inOrder(Node root)
    {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        Console.Write(root);
        inOrder(root.right);
    }
    public static Interval isOverlapping(Node root,
                                         Interval x)
    {
        if (root == null) {
            // return a dummy interval range
            return new Interval(-1, -1);
        }
        // if x overlaps with root's interval
        if ((x.low > root.range.low
             && x.low < root.range.high)
            || (x.high > root.range.low
                && x.high < root.range.high)) {
            return root.range;
        }
        else if (root.left != null
                 && root.left.max > x.low) {
            // the overlapping node may be present in left
            // child
            return isOverlapping(root.left, x);
        }
        else {
            return isOverlapping(root.right, x);
        }
    }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Javascript




class Interval {
constructor(low, high) {
this.low = low;
this.high = high;
}
 
toString() {
return "[" + this.low + "," + this.high + "]";
}
}
 
class Node {
constructor(range, max) {
this.range = range;
this.max = max;
this.left = null;
this.right = null;
}
 
toString() {
return "[" + this.range.low + ", " + this.range.high + "] " + "max = " + this.max + "\n";
}
}
 
function insert(root, x) {
if (!root) {
return new Node(x, x.high);
}
 
if (x.low < root.range.low) {
root.left = insert(root.left, x);
} else {
root.right = insert(root.right, x);
}
 
if (root.max < x.high) {
root.max = x.high;
}
 
return root;
}
 
function inOrder(root) {
if (!root) {
return;
}
 
inOrder(root.left);
console.log(root.toString());
inOrder(root.right);
}
 
function isOverlapping(root, x) {
if (!root) {
return new Interval(-1, -1);
}
 
if (x.low > root.range.low && x.low < root.range.high ||
   (x.high > root.range.low && x.high < root.range.high)) {
return root.range;
} else if (root.left != null && root.left.max > x.low) {
return isOverlapping(root.left, x);
} else {
return isOverlapping(root.right, x);
}
}
 
let root = null;
root = insert(null, new Interval(15, 20));
root = insert(root, new Interval(10, 30));
root = insert(root, new Interval(17, 19));
root = insert(root, new Interval(5, 20));
root = insert(root, new Interval(12, 15));
root = insert(root, new Interval(30, 40));
 
console.log("Inorder traversal of constructed Interval Tree is");
inOrder(root);
console.log();
 
const i = new Interval(6, 7);
console.log("Searching for interval", i);
console.log("Overlaps with ", isOverlapping(root, i));


Output

Inorder traversal of constructed Interval Tree is
[5, 20] max = 20
[10, 30] max = 30
[12, 15] max = 15
[15, 20] max = 40
[17, 19] max = 40
[30, 40] max = 40

Searching for interval [6,7]
Overlaps with [5, 20]

Time complexity of above code: O(n*h) i.e. O(n^2) in worst case as tree can be skewed.

If Interval Tree is made self-balancing like AVL Tree, then time complexity reduces to O(nlogn).
Applications of Interval Tree: 
Interval tree is mainly a geometric data structure and often used for windowing queries, for instance, to find all roads on a computerized map inside a rectangular viewport, or to find all visible elements inside a three-dimensional scene (Source Wiki).
Interval Tree vs Segment Tree 
Both segment and interval trees store intervals. Segment tree is mainly optimized for queries for a given point, and interval trees are mainly optimized for overlapping queries for a given interval.

Operations can be perform on the interval tree are:

Interval trees are a type of data structure used for organizing and searching intervals (i.e., ranges of values). The following are some of the operations that can be performed on an interval tree:

  • Insertion: Add a new interval to the tree.
  • Deletion: Remove an interval from the tree.
  • Search: Find all intervals that overlap with a given interval.
  • Query: Find the interval in the tree that contains a given point.
  • Range query: Find all intervals that overlap with a given range.
  • Merge: Combine two or more interval trees into a single tree.
  • Split: Divide a tree into two or more smaller trees based on a given interval.
  • Balancing: Maintain the balance of the tree to ensure its performance is optimized.
  • Traversal: Visit all intervals in the tree in a specific order, such as in-order, pre-order, or post-order.

In addition to these basic operations, interval trees can be extended to support more advanced operations, such as searching for intervals with a specific length, finding the closest intervals to a given point, and more. The choice of operations depends on the specific use case and requirements of the application.

algorithmic steps to implement the above operations:

  1.  Insertion:
  • Create a new node for the interval to be inserted.
    Start from the root of the tree and compare the new interval with the intervals stored in each node.
    If the new interval overlaps with the interval stored in the current node, go to the left child.
    If the new interval doesn’t overlap with the interval stored in the current node, go to the right child.
    Repeat this process until reaching a leaf node, then add the new node as a child of the leaf node.

      2.Deletion:

  • Start from the root of the tree and find the node containing the interval to be deleted.
    If the node to be deleted is a leaf node, simply remove it.
    If the node to be deleted has one child, replace it with the child.
    If the node to be deleted has two children, find the minimum interval in its right subtree, replace the interval in the node with the minimum interval, and then remove the minimum interval from the right subtree.     

      3.Search:

  • Start from the root of the tree and compare the interval to search with the intervals stored in each node.
    If the interval to search overlaps with the interval stored in the current node, add it to the result set and go to both the left and right children.
    If the interval to search doesn’t overlap with the interval stored in the current node, go to the child that could contain overlapping intervals.
    Repeat this process until reaching a leaf node, then return the result set.
     

Program –

C++




#include <iostream>
#include <algorithm>
 
struct Interval {
    int low, high;
};
 
class ITNode {
public:
    Interval *i;  // An interval stored in the node
    int max;      // Maximum high value in the node's interval and its children
    ITNode *left, *right;
 
    ITNode(Interval i) {
        this->i = new Interval(i);
        this->max = i.high;
        this->left = this->right = nullptr;
    }
};
 
class IntervalTree {
public:
    ITNode *root;
 
    IntervalTree() {
        this->root = nullptr;
    }
 
    ITNode *insert(ITNode *root, Interval i) {
        if (root == nullptr)
            return new ITNode(i);
 
        int l = root->i->low;
        if (i.low < l)
            root->left = insert(root->left, i);
        else
            root->right = insert(root->right, i);
 
        root->max = std::max(root->max, i.high);
        return root;
    }
};
 
int main() {
    IntervalTree tree;
 
    Interval intervals[] = { {15, 20}, {10, 30}, {17, 19},
                             {5, 20}, {12, 15}, {30, 40}
                           };
    int n = sizeof(intervals)/sizeof(intervals[0]);
    for (int i = 0; i < n; i++)
        tree.root = tree.insert(tree.root, intervals[i]);
 
    return 0;
}


Java




import java.util.*;
 
class Interval {
    int low, high;
 
    Interval(int low, int high)
    {
        this.low = low;
        this.high = high;
    }
}
 
class ITNode {
    Interval i; // An interval stored in the node
    int max; // Maximum high value in the node's interval
             // and its children
    ITNode left, right;
 
    ITNode(Interval i)
    {
        this.i = new Interval(i.low, i.high);
        this.max = i.high;
        this.left = this.right = null;
    }
}
 
class IntervalTree {
    ITNode root;
 
    IntervalTree() { this.root = null; }
 
    ITNode insert(ITNode root, Interval i)
    {
        if (root == null)
            return new ITNode(i);
 
        int l = root.i.low;
        if (i.low < l)
            root.left = insert(root.left, i);
        else
            root.right = insert(root.right, i);
 
        root.max = Math.max(root.max, i.high);
        return root;
    }
}
 
public class Main {
    public static void main(String[] args)
    {
        IntervalTree tree = new IntervalTree();
 
        Interval[] intervals = {
            new Interval(15, 20), new Interval(10, 30),
            new Interval(17, 19), new Interval(5, 20),
            new Interval(12, 15), new Interval(30, 40)
        };
        int n = intervals.length;
        for (int i = 0; i < n; i++)
            tree.root
                = tree.insert(tree.root, intervals[i]);
    }
}


Python3




# Python3 implementation for the above approach
 
class Interval:
    def __init__(self, low, high):
       
          # The low end of the interval
        self.low = low 
        # The high end of the interval
        self.high = high 
 
class ITNode:
    def __init__(self, i):
       
          # An interval stored in the node
        self.i = i
        # Maximum high value in the node's interval and its children
        self.max = i.high 
        # The left child of the node
        self.left = None 
        # The right child of the node
        self.right = None 
 
class IntervalTree:
    def __init__(self):
       
          # The root node of the interval tree
        self.root = None 
 
    def insert(self, root, i):
       
        if root is None:
            # If the tree is empty, create a new node and return it
            return ITNode(i)
 
        l = root.i.low
         
        if i.low < l:
              # Insert the interval into the left subtree
            root.left = self.insert(root.left, i) 
        else:
              # Insert the interval into the right subtree
            root.right = self.insert(root.right, i) 
 
        # Update the maximum high value in the node
        root.max = max(root.max, i.high) 
        return root
 
if __name__ == '__main__':
   
      # Create a new interval tree
    tree = IntervalTree() 
 
    # List of intervals to be inserted
    intervals = [Interval(15, 20), Interval(10, 30), Interval(17, 19),
                 Interval(5, 20), Interval(12, 15), Interval(30, 40)] 
    n = len(intervals)
     
    for i in range(n):
          # Insert the intervals into the tree
        tree.root = tree.insert(tree.root, intervals[i]) 
 
# This code is contributed by Amit Mangal.


Javascript




// JavaScript implementation for the above approach
 
class Interval {
 
    constructor(low, high) {
     
        // The low end of the interval
        this.low = low; 
        // The high end of the interval
        this.high = high; 
    }
}
 
class ITNode {
 
    constructor(i) {
     
        // An interval stored in the node
        this.i = i; 
        // Maximum high value in the node's interval and its children
        this.max = i.high; 
        // The left child of the node
        this.left = null
        // The right child of the node
        this.right = null
    }
}
 
class IntervalTree {
 
    constructor() {
        this.root = null// The root node of the interval tree
    }
 
    insert(root, i) {
     
        // If the tree is empty, create a new node and return it
        if (root === null) {
            return new ITNode(i); 
        }
 
        let l = root.i.low;
         
        if (i.low < l) {
            // Insert the interval into the left subtree
            root.left = this.insert(root.left, i); 
        }
        else {
            // Insert the interval into the right subtree
            root.right = this.insert(root.right, i); 
        }
 
        // Update the maximum high value in the node
        root.max = Math.max(root.max, i.high); 
        return root;
    }
}
 
// Create a new interval tree
let tree = new IntervalTree(); 
 
// List of intervals to be inserted
let intervals = [new Interval(15, 20), new Interval(10, 30), new Interval(17, 19),
                 new Interval(5, 20), new Interval(12, 15), new Interval(30, 40)]; 
                  
let n = intervals.length;
 
// Insert the intervals into the tree
for (let i = 0; i < n; i++) {
    tree.root = tree.insert(tree.root, intervals[i]); 
}
 
// This code is contributed by Amit Mangal


C#




// C# implemenatation for the above approach.
 
using System;
 
public class Interval {
    public int low;  // The low end of the interval
    public int high;  // The high end of the interval
 
    public Interval(int low, int high) {
        this.low = low;
        this.high = high;
    }
}
 
public class ITNode {
    public Interval i;  // An interval stored in the node
      // Maximum high value in the node's interval and its children
    public int max; 
    public ITNode left;  // The left child of the node
    public ITNode right;  // The right child of the node
 
    public ITNode(Interval i) {
        this.i = i;
        this.max = i.high;
        this.left = null;
        this.right = null;
    }
}
 
public class IntervalTree {
    public ITNode root;  // The root node of the interval tree
 
    public IntervalTree() {
        this.root = null;
    }
 
    public ITNode Insert(ITNode root, Interval i) {
       
        if (root == null) {
              // If the tree is empty, create a new node and return it
            return new ITNode(i); 
        }
 
        int l = root.i.low;
       
        if (i.low < l) {
              // Insert the interval into the left subtree
            root.left = Insert(root.left, i); 
        }
          else {
              // Insert the interval into the right subtree
            root.right = Insert(root.right, i); 
        }
 
          // Update the maximum high value in the node
        root.max = Math.Max(root.max, i.high); 
        return root;
    }
}
 
public class Program {
    public static void Main() {
       
          // Create a new interval tree
        IntervalTree tree = new IntervalTree(); 
 
          // List of intervals to be inserted
        Interval[] intervals = {new Interval(15, 20), new Interval(10, 30), new Interval(17, 19),
                                new Interval(5, 20), new Interval(12, 15), new Interval(30, 40)}; 
        int n = intervals.Length;
       
          // Insert the intervals into the tree
        for (int i = 0; i < n; i++) {
            tree.root = tree.Insert(tree.root, intervals[i]); 
        }
    }
}
 
// This code is contributed by Amit Mangal


Exercise: 
1) Implement delete operation for interval tree. 
2) Extend the intervalSearch() to print all overlapping intervals instead of just one. 
http://en.wikipedia.org/wiki/Interval_tree 
http://www.cse.unr.edu/~mgunes/cs302/IntervalTrees.pptx 
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest 
https://www.youtube.com/watch?v=dQF0zyaym8A

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads