Intervals and Greedy: Sort First, Then Decide Once
This lesson is for candidates in software and data coding rounds facing problems about meetings, bookings, time ranges or schedules. Most of them reduce to one move: sort the intervals, then sweep through them once making a simple decision at each step. You will learn the merge, insert and overlap-counting templates, how to choose a greedy rule, how to justify it in a sentence an interviewer accepts, and how to spot when greedy is wrong.
How interval problems are judged
The SmartIntervu coding report scores problem solving, correctness, code quality, testing and edge cases, and communication. Interval problems are decided early, in problem solving: which key you sort by, and whether touching intervals overlap. Correctness is lost on the < versus <= comparison and on shrinking a merged interval. For testing, the interviewer wants to hear an empty list, a single interval, two intervals that touch, and one interval inside another. Greedy solutions add one more question, "why is that correct?", and the communication score depends on a one-sentence answer, covered below.
How to spot an interval problem
The input is a list of pairs, each a start and an end: meetings, reservations, shifts, ranges of numbers. The question asks you to:
combine overlapping ranges,
fit a new range into an existing list,
count how many ranges are active at once, or
choose the most ranges that do not conflict.
Before anything else, ask one clarifying question: do touching intervals overlap? If one meeting ends at 10 and the next starts at 10, is that a conflict? For meetings it usually is not; for numeric ranges like [1, 2] and [2, 3] it usually is. The answer changes < to <= in every template below, and asking it shows care.
Merging overlapping intervals
Sort by start. Then each interval either overlaps the last merged one (its start is not after the last end) or begins a new group.
function mergeIntervals(intervals: [number, number][]): [number, number][] {
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
const merged: [number, number][] = [];
for (const [start, end] of sorted) {
const last = merged[merged.length - 1];
if (last !== undefined && start <= last[1]) {
last[1] = Math.max(last[1], end); // extend, never shrink
} else {
merged.push([start, end]);
}
}
return merged;
}Trace [[1, 4], [2, 5], [7, 9], [8, 8], [12, 15]]. The first two merge into [1, 5]. [7, 9] starts a new group. [8, 8] starts inside it, and Math.max keeps the end at 9; without it, the end would wrongly shrink to 8. [12, 15] stands alone. The result is [[1, 5], [7, 9], [12, 15]].
Sorting costs O(n log n) and the sweep is O(n), so the total is O(n log n). The start <= last[1] comparison treats touching intervals as overlapping; change it to < if they should not.
Inserting into a sorted list
When the list is already sorted and non-overlapping, you do not need to sort again. Walk it in three phases:
Copy every interval that ends before the new one starts.
Merge every interval that overlaps the new one, widening the new interval as you go.
Copy the rest.
function insertInterval(
sorted: [number, number][],
added: [number, number]
): [number, number][] {
const result: [number, number][] = [];
let [start, end] = added;
let i = 0;
while (i < sorted.length && sorted[i][1] < start) result.push(sorted[i++]);
while (i < sorted.length && sorted[i][0] <= end) {
start = Math.min(start, sorted[i][0]);
end = Math.max(end, sorted[i][1]);
i++;
}
result.push([start, end]);
while (i < sorted.length) result.push(sorted[i++]);
return result;
}This is O(n), and saying why ("the input is already sorted, so I skip the sort") is the point the interviewer is checking.
Counting overlaps: how many rooms?
A classic question: given meeting times, how many rooms do you need so no two meetings share one? The answer is the largest number of meetings running at the same moment.
The sweep approach sorts start times and end times separately, then walks the starts. Before placing each meeting, free every room whose meeting has already ended.
function minRooms(meetings: [number, number][]): number {
const starts = meetings.map((m) => m[0]).sort((a, b) => a - b);
const ends = meetings.map((m) => m[1]).sort((a, b) => a - b);
let rooms = 0;
let maxRooms = 0;
let e = 0;
for (const start of starts) {
while (e < ends.length && ends[e] <= start) {
rooms--; // a meeting ended at or before this start: its room is free
e++;
}
rooms++;
maxRooms = Math.max(maxRooms, rooms);
}
return maxRooms;
}Trace meetings at 9 to 10, 9 to 12, 11 to 13 and 12 to 14. At 9, two rooms. At 11, the 9 to 10 meeting has ended, so one room frees and one fills: still two. At 12, the 9 to 12 meeting ends exactly as 12 to 14 starts; <= frees the room first, so the count stays two. The answer is 2.
The alternative is a min-heap of end times: sort meetings by start, pop the earliest end if it is at or before the new start, push the new end, and track the heap's largest size. Both are O(n log n). The heap version is easier to extend if the interviewer then asks which room each meeting gets.
Greedy: one rule, applied once
A greedy algorithm makes the choice that looks best right now and never revisits it. It is fast and short, and it is correct only when you can argue that the local choice never blocks a better overall answer.
Example: keep the most non-overlapping meetings
You have a list of meeting requests and one room. Keep as many as possible; the rest are cancelled. How many must you cancel?
The rule: sort by end time, and keep each meeting that starts no earlier than the last kept one ended.
function fewestCancellations(meetings: [number, number][]): number {
const byEnd = [...meetings].sort((a, b) => a[1] - b[1]);
let kept = 0;
let lastEnd = -Infinity;
for (const [start, end] of byEnd) {
if (start >= lastEnd) {
kept++;
lastEnd = end;
}
}
return meetings.length - kept;
}Trace [[1, 4], [2, 3], [3, 5], [4, 6], [5, 7]]. Sorted by end: [2, 3], [1, 4], [3, 5], [4, 6], [5, 7]. Keep [2, 3]. Skip [1, 4], which starts at 1, before 3. Keep [3, 5]. Skip [4, 6]. Keep [5, 7]. Three kept, so two cancellations.
Now try sorting by start instead. You would keep [1, 4] first, which blocks [2, 3] and [3, 5], then keep [4, 6], which blocks [5, 7]: only two kept. The choice of sort key is the whole algorithm.
Justifying the rule: the exchange argument
Interviewers often ask "why is that correct?" You do not need a formal proof. Use the exchange argument in plain words:
"Take any best schedule. Its first meeting ends no earlier than the meeting that ends earliest overall. If I swap that first meeting for the earliest-ending one, nothing after it conflicts, because the new one ends sooner. So there is always a best schedule that starts with my choice, and the same argument repeats for the rest."
The shape works for most greedy rules: show that your choice can replace whatever an optimal answer chose, without making anything worse.
Weak and strong answers to the same question
The interviewer asks for the fewest cancellations, then, once you have code, probes with "why that sort order?"
The weak answer sorts by start because merging did, codes for eight minutes, and gets 2 kept instead of 3 on the trace above. Asked why it sorted by start, it says "that is how interval problems work". Problem solving loses points for an unexamined key, correctness for the wrong answer, and communication for an answer that explains nothing. The interviewer will usually offer a hint at this point, such as "what if you cared about when meetings finish?", and the report notes that you needed it.
The strong answer asks whether touching meetings conflict, then says before coding: "I want to leave the room free as early as possible, so I will sort by end time and keep each meeting that fits. Let me check that against sorting by start on a small case." It traces the five meetings both ways, shows 3 against 2, writes the code, and when asked "why that sort order?" gives the exchange argument above in two sentences. Same algorithm, but every scored dimension now has evidence: a chosen key, a verified result, a tested edge case and a reason.
When greedy fails
Greedy is wrong when an early choice can block a better combination later. Two signs:
The items carry different weights. Give each meeting a value and ask for the most total value instead of the most meetings. Earliest end keeps [1, 3] worth 1, which blocks [2, 10] worth 10: greedy scores 1, the best schedule scores 10. Counting meetings treats them all as equal; values break that.
Items cannot be split. Filling a bag by best value per kilogram is optimal when you may take fractions of items, and wrong when each item is all or nothing.
Before committing to a greedy rule, spend thirty seconds hunting for a counterexample on three or four small items. If you find one, switch to dynamic programming, which compares the choices instead of trusting one. If you cannot find one, say what you tried; that is evidence the interviewer can score.
What changes with seniority
A junior candidate should merge intervals correctly once the sort key is given. A mid-level candidate asks about touching intervals unprompted, picks the sort key, and solves the room count with either the sweep or the heap. A senior candidate justifies a greedy rule with the exchange argument, produces a counterexample when a proposed rule is wrong, and handles the streaming follow-up without starting over.
Follow-ups to expect
"What if the intervals arrive one at a time, as a stream?" Keep them in a balanced tree or sorted structure keyed by start, and merge with the neighbors on insert: O(log n) to find the spot, and each interval can be merged away only once, so the total stays O(n log n).
"Which room does each meeting get?" Use the heap version and store the room id alongside each end time.
"What about endpoints that are equal?" Restate your choice of
<or<=, and trace the touching case."Is your greedy rule always right?" Give the exchange argument, or the counterexample if it is not.
Mistakes that cost points
Not sorting, or sorting by the wrong key. Merging needs start order; keeping the most meetings needs end order.
Shrinking a merged interval. Always take the maximum end when merging, or a contained interval cuts the group short.
Ignoring the touching case. Decide whether equal endpoints overlap, out loud, before writing comparisons.
Mutating the caller's input. Sorting in place changes the array the caller passed. Copy first, or say you are doing it on purpose.
Claiming greedy without a reason. "It feels right" is not a justification. Give the exchange argument in one or two sentences.
Practice it
Take 15 minutes: write mergeIntervals and minRooms from memory, then test both on four cases out loud: an empty list, one interval, intervals that touch, and one interval fully inside another. Then write the fewest-cancellations rule with the wrong sort key, find the input that breaks it, and fix it.
Then start a coding interview such as Two Sum and practice stating your clarifying questions and complexity before coding. The coding quick start walks through the full method for a live round.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Two Pointers
Recognize when sorted input, in-place edits or a linked list call for two pointers, then apply the opposite-ends, reader-writer and fast-slow shapes and say why each pointer move is safe.
8 min read
- Sliding Window
Spot contiguous-range problems, run fixed and variable windows from one template, decide where to record the answer, and explain why the window breaks once values can be negative.
8 min read
- Binary Search
Write one boundary-search template without off-by-one bugs, derive exact, first, last and count searches from it, and binary search on the answer and on rotated arrays.
9 min read
- Hash Maps and Prefix Sums
Use maps for lookup, counting and grouping, build prefix sums for constant-time range queries, and count or find target-sum subarrays with a map of earlier prefixes, negatives included.
8 min read
