Many interview problems look like they need nested loops: compare every pair, check every interval against every other, group values that match. Often the fix is one line before the real work: sort the input. After that, the structure you need sits in adjacent positions, and a single left-to-right scan finishes the job. This guide shows why that works, how to write comparators that do what you mean, why stability matters when you sort by several keys, and how to recognise the pattern under time pressure.
The intuition
The picture to keep in your head.
Sorting is a way of buying locality. Before the sort, two items that interact can sit anywhere in the array, so finding them means checking pairs, which is O(n^2). After the sort, order puts related items next to each other, and you only ever need to look at the current element and a small amount of state carried from the left.
Three forms of locality come up again and again. Equal values form contiguous runs, so counting duplicates or grouping becomes a check of whether the current value equals the previous one. Closest values become neighbours: if a <= b <= c, then c - a is at least as large as both b - a and c - b, so the smallest difference in the whole set is always between two adjacent sorted elements. Intervals sorted by start time can only overlap with what came just before, so one variable tracking how far coverage has reached replaces a scan over every earlier interval.
The price is O(n log n) for the sort plus O(n) for the sweep. When the brute force is O(n^2), that trade is almost always worth it. When a hash map already gives O(n), sorting is usually the slower option unless you also need order.
Two details decide whether the trick works in practice. First, the comparator: it must return a negative number, zero or a positive number, and for several criteria it compares the first key and only falls through to the next on a tie. Second, stability: a stable sort keeps equal elements in their original relative order, which lets you rely on earlier ordering or sort in several passes from least to most important key.
Step by step
Small, safe steps, with the tests passing after each.
Step 1: Ask what should end up adjacent
Before writing code, name the relationship you need: equal values, closest values, or overlapping ranges. Pick the sort key that puts those items next to each other. For intervals that is usually the start time; for closest pairs it is the value itself.
Step 2: Write an explicit comparator
Never rely on a default sort for numbers in JavaScript or TypeScript, because it compares strings. Use
(a, b) => a - bfor numbers, or a key function in Python. For several keys, compare the first and return early unless the result is zero.Step 3: Decide whether to copy or sort in place
Sorting in place saves memory but mutates the caller's data and loses original indices. If you need the original positions later, sort an array of indices or pairs of value and index instead.
Step 4: Carry the minimum state through one scan
Walk left to right, keeping only what the next element needs: the previous value, the furthest end reached, the current run length, or the best answer so far. If you find yourself looking back more than one step, check whether the sort key is right.
Step 5: Handle the boundaries
The first element has no predecessor and the last one has no successor. Initialise state from a sensible boundary (a day's opening time, negative infinity, the first element) and remember to process whatever remains after the loop ends.
What it costs
Time and memory, and why.
- Time
- O(n log n)
- Memory
- O(n) for the sorted copy
The sort dominates at O(n log n) comparisons. The sweep visits each booking once and does constant work per booking, so it adds O(n). The code sorts a copy to avoid mutating the caller's array, which costs O(n) extra memory; sorting in place would drop that to the sort's own auxiliary space, which depends on the language (Python's Timsort can use up to O(n), for example). Without sorting, finding the gaps would require comparing each booking against all others, which is O(n^2).
A traced example
A small input, followed step by step.
Loading dock 3 at the Harbourline warehouse is open from minute 480 to 1080 (08:00 to 18:00). Bookings are half-open slots [start, end): [600,660], [480,540], [630,720], [900,960], [750,800]. Some overlap. Return the longest idle window as [start, end].
- 1
sorted = [480,540] [600,660] [630,720] [750,800] [900,960]; reach = 480; best = [480,480]Sort by start time. reach is the furthest minute covered so far and starts at opening time. best has length 0. - 2
slot [480,540]: gap 480-480 = 0; best = [480,480]; reach = 540The first booking starts exactly at opening, so there is no idle time. Coverage now reaches 540. - 3
slot [600,660]: gap 600-540 = 60; best = [540,600]; reach = 660The dock was free from 540 to 600. That 60-minute window beats 0, so it becomes the best. - 4
slot [630,720]: gap 630-660 = -30; best = [540,600]; reach = 720A negative gap means overlap. No idle time, but coverage extends to 720 because we take the maximum end. - 5
slot [750,800]: gap 750-720 = 30; best = [540,600]; reach = 800A 30-minute gap is shorter than 60, so best stays the same. - 6
slot [900,960]: gap 900-800 = 100; best = [800,900]; reach = 960A 100-minute idle window between 800 and 900 is the new best. - 7
after loop: tail gap 1080-960 = 120; best = [960,1080]The stretch after the last booking until closing is checked separately and wins with 120 minutes.
Result: [960, 1080]: the dock is idle for 120 minutes from 16:00 to 18:00.
The code
The same solution in TypeScript, Python and PHP.
type Slot = [number, number];
function longestIdleWindow(bookings: Slot[], dayStart: number, dayEnd: number): Slot {
// Sort a copy by start time so overlapping slots sit next to each other
const sorted = [...bookings].sort((a, b) => a[0] - b[0]);
let reach = dayStart; // furthest minute covered so far
let best: Slot = [dayStart, dayStart];
for (const [start, end] of sorted) {
// A gap exists only if this slot starts after everything seen so far ends
if (start - reach > best[1] - best[0]) {
best = [reach, start];
}
reach = Math.max(reach, end);
}
// The stretch after the last booking until closing time
if (dayEnd - reach > best[1] - best[0]) {
best = [reach, dayEnd];
}
return best;
}
const bookings: Slot[] = [[600, 660], [480, 540], [630, 720], [900, 960], [750, 800]];
console.log(longestIdleWindow(bookings, 480, 1080)); // [960, 1080]def longest_idle_window(bookings, day_start, day_end):
# Sort a copy by start time so overlapping slots sit next to each other
sorted_slots = sorted(bookings, key=lambda slot: slot[0])
reach = day_start # furthest minute covered so far
best = [day_start, day_start]
for start, end in sorted_slots:
# A gap exists only if this slot starts after everything seen so far ends
if start - reach > best[1] - best[0]:
best = [reach, start]
reach = max(reach, end)
# The stretch after the last booking until closing time
if day_end - reach > best[1] - best[0]:
best = [reach, day_end]
return best
bookings = [[600, 660], [480, 540], [630, 720], [900, 960], [750, 800]]
print(longest_idle_window(bookings, 480, 1080)) # [960, 1080]<?php
function longestIdleWindow(array $bookings, int $dayStart, int $dayEnd): array
{
// Sort a copy by start time so overlapping slots sit next to each other
$sorted = $bookings;
usort($sorted, fn($a, $b) => $a[0] <=> $b[0]);
$reach = $dayStart; // furthest minute covered so far
$best = [$dayStart, $dayStart];
foreach ($sorted as [$start, $end]) {
// A gap exists only if this slot starts after everything seen so far ends
if ($start - $reach > $best[1] - $best[0]) {
$best = [$reach, $start];
}
$reach = max($reach, $end);
}
// The stretch after the last booking until closing time
if ($dayEnd - $reach > $best[1] - $best[0]) {
$best = [$reach, $dayEnd];
}
return $best;
}
$bookings = [[600, 660], [480, 540], [630, 720], [900, 960], [750, 800]];
echo json_encode(longestIdleWindow($bookings, 480, 1080)), PHP_EOL; // [960,1080]Variants
Shapes the same idea takes.
Adjacent comparison
When: You need duplicates, run lengths, or the closest pair of values.
Sort by value, then compare each element only with the one before it. Equal values form runs, and the minimum difference is always between neighbours, so tracking the previous element is enough. Reach for a hash set instead if you only need membership and order does not matter.
Interval sweep with a reach variable
When: Ranges may overlap and you need merged blocks, gaps, total coverage, or a conflict check.
Sort by start. Keep the furthest end seen so far. If the next start is beyond it, a new block begins; otherwise extend with max. Using max rather than the last end handles a long interval that swallows several shorter ones.
Multi-key comparator
When: Order depends on several criteria, for example support tickets by priority descending, then by creation time ascending.
Compare the primary key; only if it ties, compare the next. In TypeScript:
(a, b) => b.priority - a.priority || a.createdAt - b.createdAt. In Python, a key tuple with a negated numeric field does the same:key=lambda t: (-t.priority, t.created_at). For strings, uselocaleComparein TypeScript and<=>orstrcmpin PHP.Multi-pass stable sort
When: A descending string key cannot be negated, or keys arrive from separate UI controls.
With a stable sort, sort by the least important key first and the most important key last. Each later pass keeps earlier order among ties. Python's sort, JavaScript's Array.prototype.sort since ES2019 and PHP's sort functions since PHP 8.0 are all stable.
Sorting indices instead of values
When: The answer must refer to original positions, such as which input rows conflict.
Build an array of indices and sort it by the value at each index, or sort pairs of value and index. The sweep then reads values through the indices and can report original positions without losing them.
Common mistakes
What usually goes wrong and how to avoid it.
Avoid
Calling
sort()on numbers in JavaScript or TypeScript without a comparator.Better
The default compares values as strings, so
[10, 9].sort()stays[10, 9]and[5, 25, 100]becomes[100, 25, 5]. Always pass(a, b) => a - bfor numbers.Avoid
Returning a boolean from a comparator, such as
(a, b) => a > b.Better
Comparators must return negative, zero or positive. A boolean maps to 0 or 1 and never signals 'less than', which gives wrong or engine-dependent results. Return
a - b, or use<=>in PHP.Avoid
Updating the reach with the current interval's end instead of the maximum.
Better
An interval like [100, 500] followed by [120, 200] would shrink the reach to 200 and invent a false gap. Always use
reach = max(reach, end).Avoid
Forgetting the work that remains after the loop.
Better
Sweeps leave a final block, run or gap unprocessed when the loop ends. In the trace, the winning idle window was the tail after the last booking. Add an explicit check after the loop.
Avoid
Mixing up open and closed interval ends.
Better
Decide whether [10, 20] and [20, 30] touch or overlap. With half-open slots they touch and leave a zero gap; with closed ranges they overlap. State the convention aloud and test the touching case.
Avoid
Writing a multi-key comparator that ignores ties.
Better
Sorting only by the primary key leaves ties in whatever order the input had. If the problem defines a tie-breaker, encode it with
||in TypeScript, a tuple key in Python, or a chained<=>with?:in PHP.
How to recognise it
Clues in a problem statement that call for it.
- The brute force compares every pair, and the pairs that matter are the ones with close or equal values.
- The input is a list of ranges, bookings, shifts or time windows that may overlap.
- You need groups of equal items and the output can be in any order, or should be in sorted order anyway.
- The problem asks for a minimum difference, a closest pair, or the largest gap between values.
- The output must be ranked by one criterion with a tie-breaker on another.
- A greedy choice becomes obvious once items are processed in order of deadline, start time or size.
- Original indices are not required in the answer, or can be carried alongside values.
Common questions
Short answers to the usual doubts.
Why is the smallest difference always between neighbours after sorting?
Take sorted values a <= b <= c. Then c - a = (c - b) + (b - a), which is at least as large as either part. So any non-adjacent pair has a difference at least as large as some adjacent pair between them, and checking only neighbours finds the minimum.
When should I not sort first?
When a hash map or set already solves the problem in O(n) and you do not need order, such as checking for any duplicate or finding a pair with a target sum. Also when values come from a small known range: counting sort or bucket counting can beat O(n log n).
Does stability matter if I write a full multi-key comparator?
Not for the keys you encode. If the comparator breaks every tie the problem defines, the order is fully determined. Stability matters when items can still compare equal and you want their input order preserved, or when you sort in several passes.
Is it fine to sort the input array in place during an interview?
Usually yes, but say so. It saves memory and interviewers rarely object, but it changes the caller's data and loses original positions. If the function's contract suggests the input is read-only, sort a copy and mention the O(n) trade-off.
Should I sort intervals by start or by end?
Sort by start to merge intervals, find gaps or compute coverage, because each new interval can only connect to the block you are building. Sort by end for greedy selection problems, such as choosing the most non-overlapping intervals, because finishing early leaves the most room for the rest.
Can subtraction in a comparator overflow?
In TypeScript, Python and PHP with typical values, no: JavaScript numbers are doubles, Python integers are unbounded, and PHP integers are 64-bit. In languages with 32-bit ints, such as Java, a - b can overflow for extreme values, so use a built-in compare function there.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Leaderboard by score and nameSolve the problem
- Merge overlapping bookingsSolve the problem
- Improve this: the smallest gapSolve the problem