DEPLOYEDAI-era interview training
RankBootstrapping
XP 0 / 250
0
0%
Ready
Coding Interview: Patterns & DSA · Sorting, Searching & Heaps · Lesson 3 of 3

Greedy & interval patterns

7 min

A greedy algorithm makes the locally best choice at each step and never revisits it. Greedy is only correct when you can argue the local pick is safe — usually an exchange argument: any optimal solution can be rewritten to include your choice without getting worse. Say that argument out loud; 'greedy because it feels right' is how candidates fail these.

  • Interval scheduling: to attend the most non-overlapping meetings, sort by end time and always take the earliest-ending compatible one — it leaves the most room for everything after it.
  • Jump game: one pass tracking the furthest reachable index; if your position ever exceeds it, you are stuck — O(n).
  • Kadane's (maximum subarray): at each element, either extend the running sum or restart at the element (cur = max(x, cur + x)), tracking the best — O(n), handles all-negative arrays.

Merge overlapping intervals

The interval workhorse: sort by start, then sweep once, either extending the last merged interval or appending a new one. Sorting dominates the cost: O(n log n).

def merge(intervals):
    intervals.sort(key=lambda iv: iv[0])
    out = []
    for start, end in intervals:
        if out and start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)   # overlap -> extend
        else:
            out.append([start, end])            # gap -> start fresh
    return out
Which key you sort by is the answerMerging sorts by start; scheduling the most non-overlapping sorts by end. Mixing them up produces plausible-looking wrong answers — state which key and why before coding.
Recognize itIntervals are the tell for merge/insert interval, meeting rooms, non-overlapping intervals: sort, then sweep (add a min-heap of end times for 'how many rooms'). Greedy is the tell for maximize/minimize a count where a sort order makes each local pick provably safe.

◆ Lock it in

  • Greedy needs a safe-choice argument (exchange argument) — say it, don't assume it.
  • Intervals: sort by start to merge, sort by end to schedule the most non-overlapping.
  • Kadane's: extend or restart the running sum — maximum subarray in O(n).
Feynman drill — say it out loudExplain why sorting by end time (not start time or duration) picks the maximum number of non-overlapping meetings.
Step 1 rate your confidence · Step 2 pick your answer
To attend the MAXIMUM number of non-overlapping meetings, you sort the intervals by:
Step 1 — how sure are you?