Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Practice · Coding

Intervals

Sort by start to merge and count overlaps; sort by end to choose. One sorted pass replaces checking every pair.


When it applies

merged block merged block gap sort by start; a start after the block ends opens a new block

Use the interval pattern whenever the input is a list of ranges: bookings, meetings, trading sessions, time windows, segments on a line. The pairwise check, does this one overlap that one, is O(n²); sorting first makes every overlap appear next to the range it overlaps, and one pass handles them.

Which sort depends on the question. Sort by start to merge ranges or measure what they cover: a range that starts after the current block ends opens a new block. Sort by end to choose the most non-overlapping ranges: the one that ends earliest leaves the most room. Sort starts and ends separately to count how many are open at once, as a sweep line over +1 and −1 events.

Signals: "intervals", "bookings", "meetings", "overlap", "merge", "rooms", "schedule", "covered". When the ranges carry values and you must choose the best set, the order still comes from sorting by end, and the choice becomes dynamic programming.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

intervals.sort()                       # by start
merged = []
for s, e in intervals:
    if merged and s <= merged[-1][1]:      # overlaps the current block
        merged[-1][1] = max(merged[-1][1], e)
    else:                                  # a gap: start a new block
        merged.append([s, e])

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.