Compile Ready
Module 1 · Interval Fundamentals

Sorting Intervals

Sorting intervals turns a global geometry problem into a left-to-right sequence of local boundary decisions.

8 min readConcept
IntervalsSortingComparatorGreedy

Why Sorting Is Almost Always First

Unsorted intervals hide the nearest competitor. If [8,10] appears before [1,3] and [2,6], a merge algorithm cannot know whether the current interval is final. Sorting establishes a direction so the next interval is the only new boundary that can affect the current decision.

After sorting, many interval problems become sweeps. You carry a current merged range, a chosen end boundary, or a room count, then update it with the next interval. The cost is usually O(n log n) for sorting, followed by an O(n) scan.

Sort by Start for Building Ranges

When the task is to merge, insert, or produce actual combined intervals, sort by start. This makes intervals arrive in the order they begin on the number line. For [1,3], [2,6], [8,10], the carried interval can only be extended by a later start; no unseen interval begins before 1 after the sort.

This is why Merge Intervals and Insert Interval use start order. The algorithm needs to know whether the next interval begins before the current carried interval ends. Sorting by end would lose the clean left boundary needed to emit merged ranges in order.

Sort by End for Greedy Selection

When the task is to keep as many non-overlapping intervals as possible, remove the fewest, or place the minimum number of arrows, sort by end. The greedy choice is usually to commit to the interval that finishes earliest because it leaves the most room for future intervals.

For example, with [1,10], [2,3], and [4,5], choosing the long interval first blocks two smaller compatible choices. Sorting by end considers [2,3] before [4,5], which is the structure behind Non-overlapping Intervals and Minimum Arrows to Burst Balloons.

Comparator Discipline in Java

You will often see Arrays.sort(intervals, (a, b) -> a[0] - b[0]) in examples. It is compact and works for small endpoint ranges, but subtraction can overflow when values are near integer limits. Overflow can reverse the ordering and make the sweep silently wrong.

Prefer Integer.compare(a[0], b[0]) for start order and Integer.compare(a[1], b[1]) for end order. If ties matter, add a secondary comparison deliberately, such as sorting by start then end. A comparator is not just syntax; it defines the geometry your algorithm will see.

Overflow-safe interval comparators

Loading…

Use start order when constructing merged ranges, and end order when the greedy proof depends on finishing as early as possible.

Key Takeaways

  • Sorting makes interval decisions local by imposing a number-line order.
  • Use start order for merge, insert, and output construction problems.
  • Use end order for greedy selection problems that keep or hit intervals.
  • Prefer Integer.compare over subtraction when endpoint values may be large.