Algorithmic patterns · 12 / 15 Exercise Hard

Merge intervals

Objective

If you sort the intervals by their start, the overlapping ones end up next to each other and one pass is enough to merge them: each interval joins the last one if it starts before the last one ends.

Instructions

  • The first line has the number n of intervals; then come n lines start end.
  • Show the intervals resulting from merging those that overlap or touch, sorted, one per line.
Input
4
1 3
2 6
8 10
15 18
Output
1 6
8 10
15 18

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise