Interval Problems

Medium 20 min read

Interval Problems Made Simple

Master interval algorithms through interactive visualizations! Learn how calendar apps schedule meetings, ride-sharing services match drivers, and streaming platforms manage bandwidth.

⏱️ 30-45 mins 📊 Intermediate Level 🎮 5 Interactive Demos 💡 Real-world Applications

Why Should You Care About Interval Problems?

Interval problems are everywhere in modern technology! Let's see where you encounter them daily:

📅

Calendar Apps (Google Calendar, Outlook)

When you schedule a meeting, calendar apps use interval algorithms to check for conflicts, suggest available times, and handle recurring events. They merge overlapping events and find free slots!

🚗

Uber/Lyft Driver Matching

Ride-sharing apps use interval algorithms to match drivers with riders based on time windows. They optimize driver schedules to minimize wait times and maximize rides per hour.

🏨

Hotel & Flight Booking

Booking.com and airlines use interval algorithms to manage room/seat availability, prevent double bookings, and optimize pricing based on demand periods.

📺

Netflix Bandwidth Management

Streaming services use interval algorithms to schedule content delivery, manage server load during peak hours, and pre-buffer content based on viewing patterns.

🏥

Hospital Scheduling

Healthcare systems use interval algorithms to schedule surgeries, manage operating room availability, and ensure critical resources don't have conflicts.

The Basics - Let's Start Simple!

What is an Interval?

Think of an interval like a time slot on your calendar - it has a start time and an end time. Like booking a meeting room from 2 PM to 3 PM, that's the interval [2, 3]!

Visual Timeline Example

Try It: Create Your Own Intervals

Enter start and end times to see intervals on a timeline:

Your First Interval Algorithm - Check Overlap! 🎯
# Let's check if two meetings conflict! def do_intervals_overlap(interval1, interval2): # Think of it like: "Do these two meetings conflict?" start1, end1 = interval1 start2, end2 = interval2 # They overlap if one starts before the other ends! return start1 < end2 and start2 < end1 # Example: Your meetings meeting1 = [9, 11] # 9 AM to 11 AM meeting2 = [10, 12] # 10 AM to 12 PM if do_intervals_overlap(meeting1, meeting2): print("❌ Conflict! These meetings overlap!") else: print("✅ No conflict! You can attend both!")

Common Mistake: Edge Cases

# ❌ WRONG - Forgetting about touching intervals def bad_overlap_check(interval1, interval2): return interval1[0] < interval2[1] and interval2[0] < interval1[1] # This says [1,2] and [2,3] overlap, but they just touch!

Why it matters: Meeting from 1-2 PM and another from 2-3 PM don't actually conflict!

The Right Way

# ✅ CORRECT - Use <= for touching intervals def correct_overlap_check(interval1, interval2): # For meetings: use < (touching is OK) # For resources: use <= (can't share even for a moment) return interval1[0] < interval2[1] and interval2[0] < interval1[1]

Common Interval Patterns

Intermediate

Merge Overlapping Intervals - The Calendar Cleaner!

Imagine combining all your overlapping meetings into single blocks. This is what merge intervals does!

Interactive Merge Intervals

Add intervals and watch them merge automatically:

Merge Intervals - Clean Up Your Calendar! 📅
# Merge all overlapping time slots - perfect for calendar apps! def merge_intervals(intervals): """Like combining overlapping meetings into one big meeting""" if not intervals: return [] # Step 1: Sort by start time (earliest meeting first) intervals.sort(key=lambda x: x[0]) # Step 2: Start with the first interval merged = [intervals[0]] # Step 3: Check each interval for current in intervals[1:]: last_merged = merged[-1] if current[0] <= last_merged[1]: # They overlap! Extend the last merged interval merged[-1] = [last_merged[0], max(last_merged[1], current[1])] else: # No overlap, add as new interval merged.append(current) return merged # Example: Your busy day meetings = [[1,3], [2,6], [8,10], [15,18]] merged = merge_intervals(meetings) print(f"Your consolidated schedule: {merged}") # Output: [[1,6], [8,10], [15,18]] - Much cleaner! 🎉
Intermediate

Meeting Rooms - Can You Attend All Meetings?

This is like checking if you can be in multiple places at once (spoiler: you can't!).

Meeting Room Scheduler 🏢
# Check if one person can attend all meetings def can_attend_all_meetings(intervals): """Are you trying to be in two places at once?""" # Sort meetings by start time intervals.sort(key=lambda x: x[0]) # Check each pair of consecutive meetings for i in range(1, len(intervals)): if intervals[i][0] < intervals[i-1][1]: # Oops! This meeting starts before the previous one ends return False return True # You're good to go! ✅ # How many meeting rooms do we need? def min_meeting_rooms(intervals): """Like finding how many conference rooms to book""" if not intervals: return 0 # Separate start and end times starts = sorted([i[0] for i in intervals]) ends = sorted([i[1] for i in intervals]) rooms = 0 max_rooms = 0 s = e = 0 while s < len(starts): if starts[s] < ends[e]: # A meeting starts - need a room! rooms += 1 s += 1 else: # A meeting ends - room becomes free! rooms -= 1 e += 1 max_rooms = max(max_rooms, rooms) return max_rooms # Example: Company meetings meetings = [[0,30], [5,10], [15,20]] print(f"Rooms needed: {min_meeting_rooms(meetings)}") # Output: 2

Practice Problems

Beginner

Problem 1: Insert Interval

You have a sorted list of non-overlapping intervals and need to insert a new one. Merge if necessary!

Think About It First!

It's like adding a new meeting to your calendar and combining any overlaps.

Show Solution
def insert_interval(intervals, new_interval): result = [] i = 0 # Add all intervals before the new one while i < len(intervals) and intervals[i][1] < new_interval[0]: result.append(intervals[i]) i += 1 # Merge overlapping intervals while i < len(intervals) and intervals[i][0] <= new_interval[1]: new_interval[0] = min(new_interval[0], intervals[i][0]) new_interval[1] = max(new_interval[1], intervals[i][1]) i += 1 result.append(new_interval) # Add remaining intervals while i < len(intervals): result.append(intervals[i]) i += 1 return result # Test it! intervals = [[1,3], [6,9]] new = [2,5] print(insert_interval(intervals, new)) # [[1,5], [6,9]]
Intermediate

Problem 2: Employee Free Time

Find common free time slots when all employees are available for a meeting.

Think About It First!

Merge all busy times, then find the gaps!

Show Solution
def employee_free_time(schedules): # Collect all busy intervals all_intervals = [] for employee in schedules: all_intervals.extend(employee) # Sort and merge all busy times all_intervals.sort(key=lambda x: x[0]) merged = [all_intervals[0]] for interval in all_intervals[1:]: if interval[0] <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], interval[1]) else: merged.append(interval) # Find gaps (free time) free_time = [] for i in range(1, len(merged)): free_time.append([merged[i-1][1], merged[i][0]]) return free_time # Example: 3 employees' schedules schedules = [ [[1,3], [6,7]], # Employee 1 [[2,4]], # Employee 2 [[2,5], [9,12]] # Employee 3 ] print(employee_free_time(schedules)) # [[5,6], [7,9]]
Advanced

Problem 3: Maximum CPU Load

Given jobs with start time, end time, and CPU load, find the maximum CPU load at any time.

Think About It First!

Track when jobs start and end, maintaining current load!

Show Solution
def max_cpu_load(jobs): # Create events for job starts and ends events = [] for start, end, load in jobs: events.append((start, load, 'start')) events.append((end, -load, 'end')) # Sort events by time events.sort(key=lambda x: (x[0], x[2] == 'start')) current_load = 0 max_load = 0 for time, load_change, event_type in events: current_load += load_change max_load = max(max_load, current_load) return max_load # Example: Server jobs jobs = [ [1, 4, 3], # Job 1: time 1-4, load 3 [2, 5, 4], # Job 2: time 2-5, load 4 [7, 9, 6] # Job 3: time 7-9, load 6 ] print(f"Max CPU load: {max_cpu_load(jobs)}") # Output: 7

Advanced Techniques

Advanced

Sweep Line Algorithm

Imagine a vertical line sweeping across a timeline, processing events as it goes. Perfect for complex interval problems!

Sweep Line for Skyline Problem 🏙️
# Find the skyline formed by buildings import heapq def get_skyline(buildings): """Each building: [left, right, height]""" events = [] # Create events for building starts and ends for left, right, height in buildings: events.append((left, -height, 'start')) # Negative for max heap events.append((right, height, 'end')) events.sort() result = [] heights = [0] # Ground level for x, h, event_type in events: if event_type == 'start': heapq.heappush(heights, h) else: heights.remove(-h) heapq.heapify(heights) # Check if max height changed max_height = -heights[0] if not result or result[-1][1] != max_height: result.append([x, max_height]) return result
Advanced

Calendar with Multiple Bookings

Build a calendar that can handle single, double, or even triple bookings!

Smart Calendar Implementation 📅
class MyCalendarTwo: """Calendar allowing at most double booking""" def __init__(self): self.bookings = [] # All bookings self.overlaps = [] # Double-booked slots def book(self, start, end): # Check if it would cause triple booking for s, e in self.overlaps: if start < e and end > s: return False # Would be triple booked! # Add overlaps with existing bookings for s, e in self.bookings: if start < e and end > s: overlap_start = max(start, s) overlap_end = min(end, e) self.overlaps.append([overlap_start, overlap_end]) self.bookings.append([start, end]) return True # Usage example calendar = MyCalendarTwo() print(calendar.book(10, 20)) # True print(calendar.book(50, 60)) # True print(calendar.book(10, 40)) # True (double booking OK) print(calendar.book(5, 15)) # False (would be triple)

Quick Reference

Algorithm Comparison Chart

Algorithm Time Complexity When to Use Plain English Speed
Merge Intervals O(n log n) Combine overlapping ranges ⚡ Quick for any size
Insert Interval O(n) Add to sorted intervals 💨 Super fast
Meeting Rooms O(n log n) Check scheduling conflicts ⚡ Quick with sorting
Meeting Rooms II O(n log n) Find min resources needed ⚡ Efficient for scheduling
Employee Free Time O(n log n) Find common availability ⚡ Scales well
Sweep Line O(n log n) Complex interval events 🚀 Powerful for hard problems

Common Patterns & Tips

1
Sort First: Most interval problems need sorting by start time
2
Check Overlap: Use start1 < end2 AND start2 < end1
3
Merge Logic: Keep extending the end time when overlapping
4
Sweep Line: Process events in order for complex scenarios

Common Pitfalls to Avoid

Pitfall #1: Forgetting Edge Cases

Always consider: empty input, single interval, all overlapping, none overlapping

Pitfall #2: Off-by-One Errors

Be clear: are intervals [start, end] inclusive or [start, end) exclusive?

Pitfall #3: Not Sorting First

Most interval algorithms require sorted input - don't forget this step!