Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 1 Updated

Merge Intervals

Sort by start, merge adjacent overlaps in one pass.

  • Full 6m
  • Revision 2m
  • Flow 2m

Merge Intervals — control flow

flowchart TD
    S["<b>i · sort</b><br/>intervals.sort(key=x[0])"]
      --> I["<b>ii · init</b><br/>merged = [intervals[0]]"]
      --> L{"<b>iii · next interval?</b><br/>for s, e in intervals[1:]"}
    L -->|"yes"| C{"<b>iv · overlap?</b><br/>s ≤ merged[-1][1]?"}
    C -->|"yes"| M["<b>v · extend</b><br/>merged[-1][1] = max(merged[-1][1], e)"]
    C -->|"no"| N["<b>vi · new bucket</b><br/>merged.append([s, e])"]
    M --> L
    N --> L
    L -->|"done"| R["<b>return</b> merged"]
 
    classDef start fill:#f5efe1,stroke:#6a8a4f,stroke-width:2px,color:#1a1915;
    classDef decision fill:#fdecd3,stroke:#c2410c,stroke-width:2px,color:#1a1915;
    classDef action fill:#e7efd9,stroke:#587640,stroke-width:2px,color:#1a1915;
    class S,I start
    class L,C decision
    class M,N,R action
  • Sort by start

    Puts overlapping intervals next to each other. This is why the rest of the algorithm is a single linear scan.

  • Seed the output

    `merged = [intervals[0]]`. The first interval is always the first bucket.

  • Iterate

    Walk intervals from index 1 onwards.

  • Overlap check

    `s ≤ merged[-1][1]`. `≤` (not `<`) so touching endpoints `[1,2] + [2,3]` merge.

  • Extend

    `merged[-1][1] = max(merged[-1][1], e)`. The `max` handles containment for free.

  • New bucket

    No overlap — push `[s, e]` as a fresh bucket. Return `merged` when done.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.