DSA Master › Topic 6
Sorting & Intervals
Sorting often turns a hard problem into a linear scan. For intervals, sort by start to merge them, or by end for greedy scheduling (keep as many non-overlapping intervals as possible).
Concepts
- Custom comparators
- Merge sort
- Quicksort
- Interval merging
- Sorting by endpoints
How to recognise it
- The input is a list of [start, end] pairs.
- You need to merge, insert, count overlaps or remove the fewest intervals.
- The answer depends on a custom ordering, like "Largest Number".
Common pitfalls
- Use Integer.compare in comparators. a - b can overflow.
- Check whether touching intervals ([1,2] and [2,3]) count as overlapping in that problem.
Problems
- Merge Intervals (Medium)
- Insert Interval (Medium)
- Non-overlapping Intervals (Medium)
- Meeting Rooms II (Medium, Premium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Largest Number (Medium)
- Sort an Array (Medium)