Merge Overlapping & Adjacent Intervals

Difficulty: Medium · Unit 3: Built-in Data Structures & Hashing · Featured in: CodeTantra Lab Pattern

Given N closed intervals [start, end], merge all overlapping or touching intervals (two intervals [a, b] and [c, d] merge if c <= b) and output the merged intervals sorted by start time.

Input & Output Format

Input: Line 1: integer N. Next N lines: two space-separated integers start and end.

Output: Print one merged interval `start end` per line.

Sample 1

4
1 3
2 6
8 10
15 18
1 6
8 10
15 18

[1, 3] and [2, 6] overlap and merge into [1, 6].

Free forever — sign in with email at poorvithmp.com to unlock the dry run, verified Python 3 solution, edge-case traps, and downloads.

Back to Python Notes Hub