ADVANCED DATA STRUCTURES PROGRAM • LEVEL 14 — BALANCED BINARY SEARCH TREES
Find an Overlap with an Interval Tree
Learn how to find an overlap with an interval tree using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Overlap = [5,20]
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
struct Node { int low, high, maximum; struct Node *left, *right; };
struct Node *insert_interval(struct Node *root, int low, int high) { if (!root) { root = malloc(sizeof *root); if (!root) exit(EXIT_FAILURE); root->low = low; root->high = root->maximum = high; root->left = root->right = NULL; return root; } if (low < root->low) root->left = insert_interval(root->left, low, high); else root->right = insert_interval(root->right, low, high); if (high > root->maximum) root->maximum = high; return root; }
struct Node *overlap(struct Node *root, int low, int high) { while (root && (root->high < low || high < root->low)) { if (root->left && root->left->maximum >= low) root = root->left; else root = root->right; } return root; }
void free_intervals(struct Node *root) { if (root) { free_intervals(root->left); free_intervals(root->right); free(root); } }
int main(void)
{
int intervals[][2] = {{15,20},{10,30},{17,19},{5,20},{12,15},{30,40}}; struct Node *root = NULL;
for (int i = 0; i < 6; i++) root = insert_interval(root, intervals[i][0], intervals[i][1]);
struct Node *match = overlap(root, 6, 7); printf("Overlap = [%d,%d]\n", match->low, match->high); free_intervals(root); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Overlap = [5,20]
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use each subtree's maximum high endpoint to discard branches that cannot overlap the query.
- Display the computed result.
Use each subtree's maximum high endpoint to discard branches that cannot overlap the query.
EFFICIENCY
Time and space complexity
Time complexity
O(h)
Auxiliary space
O(h)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
