Skip to content
We areTOP 1%
DSA · Pro · Pattern 5 of 9

Intervals & Sweep Line

12 problems.
Your progress0%
1st Visit
0/12
2nd Visit
0/12
Revise
0/12

About this pattern

Interval problems describe ranges such as meetings, bookings, segments or trips. Sorting by start, or by end for greedy selection, brings overlapping ranges next to each other so they can be merged, intersected or counted in a single pass. A sweep line goes further: turn each interval into a +1 event at its start and a -1 event just after its end, sort the events, and scan them while keeping a running count. That count reveals the maximum overlap or the total length covered by exactly k intervals. A difference array does the same job when coordinates are small. Expect O(n log n) for sorting and linear work afterwards.

// Maximum number of closed intervals [l, r] that cover one point
int maxOverlap(const vector<pair<int, int>>& segs) {
    vector<pair<int, int>> ev;                // {coordinate, +1 or -1}
    for (auto [l, r] : segs) {
        ev.push_back({l, +1});
        ev.push_back({r + 1, -1});            // the interval stops covering at r + 1
    }
    sort(ev.begin(), ev.end());               // -1 sorts before +1 at equal x
    int cur = 0, best = 0;
    for (auto [x, d] : ev) {
        cur += d;
        best = max(best, cur);
    }
    return best;
}

Problems

Intervals & Sweep Line questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Merge IntervalsLeetCodeMedium Solve Merge Intervals on LeetCode (opens in a new tab)
2Insert IntervalLeetCodeMedium Solve Insert Interval on LeetCode (opens in a new tab)
3Non-overlapping IntervalsLeetCodeMedium Solve Non-overlapping Intervals on LeetCode (opens in a new tab)
4Interval List IntersectionsLeetCodeMedium Solve Interval List Intersections on LeetCode (opens in a new tab)
5Car PoolingLeetCodeMedium Solve Car Pooling on LeetCode (opens in a new tab)
6Divide Intervals Into Minimum Number of GroupsLeetCodeMedium Solve Divide Intervals Into Minimum Number of Groups on LeetCode (opens in a new tab)
7Little Girl and Maximum SumCodeforcesMedium 1500Solve Little Girl and Maximum Sum on Codeforces (opens in a new tab)
8Maximal IntersectionCodeforcesMedium 1600Solve Maximal Intersection on Codeforces (opens in a new tab)
9Covered Points CountCodeforcesMedium 1700Solve Covered Points Count on Codeforces (opens in a new tab)
10Painting the FenceCodeforcesMedium 1700Solve Painting the Fence on Codeforces (opens in a new tab)
11The Treasure of The SegmentsCodeforcesHard 1800Solve The Treasure of The Segments on Codeforces (opens in a new tab)
12Minimum Interval to Include Each QueryLeetCodeHard Solve Minimum Interval to Include Each Query on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account