Intervals

Phase 2 7 solutions

Intervals

mindmap
  root((Intervals))
    Merge/Insert
      Merge Intervals LC56
      Insert Interval LC57
    Scheduling Rooms
      Meeting Rooms LC252
      Meeting Rooms II LC253
      Meeting Rooms III LC2402
    Sweep Line
      Non-Overlapping Intervals LC435
    Query-Based
      Minimum Interval to Include Each Query LC1851

Problem List

# Problem LC # Difficulty Key Technique
1 Insert Interval 57 Medium Linear scan + merge
2 Merge Intervals 56 Medium Sort + merge
3 Non-Overlapping Intervals 435 Medium Greedy scheduling
4 Meeting Rooms 252 Easy Sort + check overlap
5 Meeting Rooms II 253 Medium Min-heap
6 Meeting Rooms III 2402 Hard Two heaps
7 Minimum Interval to Include Each Query 1851 Hard Sort + heap + offline queries

Interval Problem Decision Tree

flowchart TD
    A[Interval Problem] --> B{"What is asked?"}
    B --> C["Merge / Insert"]
    B --> D["Count rooms / resources"]
    B --> E[Remove minimum intervals]
    B --> F[Answer queries]

    C --> C1[Sort by start, linear merge]
    C --> C2[Insert Interval #57 — binary search + merge]

    D --> D1[Sort by start, min-heap on end times]
    D1 --> D2[Meeting Rooms II #253]
    D1 --> D3[Meeting Rooms III #2402 — two heaps]

    E --> E1[Sort by end, greedy keep earliest end]
    E1 --> E2[Non-Overlapping Intervals #435]

    F --> F1[Offline: sort queries + sweep with heap]
    F1 --> F2[Min Interval per Query #1851]

Merge Intervals Algorithm Flow

flowchart TD
    A[Sort intervals by start time] --> B[result = first interval]
    B --> C[For each remaining interval]
    C --> D{"current.start <= last.end?"}
    D -- Yes --> E[Merge: last.end = max of last.end and current.end]
    D -- No --> F[Append current to result as new interval]
    E --> G{"More intervals?"}
    F --> G
    G -- Yes --> C
    G -- No --> H[Return result]

    style A fill:#2d6a4f,color:#fff
    style H fill:#1b4332,color:#fff

Sweep Line / Event-Based Approach

flowchart TD
    A[For each interval, emit start +1 and end -1 events] --> B[Sort all events by time]
    B --> C[active = 0, maxActive = 0]
    C --> D[For each event in order]
    D --> E[active += event.delta]
    E --> F[maxActive = max of maxActive and active]
    F --> G{"More events?"}
    G -- Yes --> D
    G -- No --> H[Return maxActive]

    style A fill:#2d6a4f,color:#fff
    style H fill:#1b4332,color:#fff

Used for: counting max concurrent meetings (Meeting Rooms II alternative)


Meeting Rooms Heap Approach

flowchart TD
    A[Sort meetings by start time] --> B[min-heap = empty, rooms = 0]
    B --> C[For each meeting start, end]
    C --> D{"heap not empty AND heap.top <= start?"}
    D -- Yes --> E[Pop earliest ending room — reuse it]
    D -- No --> F[No room free — allocate new room]
    E --> G[Push end time to heap]
    F --> G
    G --> H{"More meetings?"}
    H -- Yes --> C
    H -- No --> I[Return heap size = rooms needed]

    style A fill:#2d6a4f,color:#fff
    style I fill:#1b4332,color:#fff

Interval Overlap Detection Logic

flowchart TD
    A[Two intervals A = a1,a2 and B = b1,b2] --> B{"Do they overlap?"}
    B --> C["Overlap condition: a1 <= b2 AND b1 <= a2"]
    C --> D{"True?"}
    D -- Yes --> E[Overlapping — merged = min a1 b1, max a2 b2]
    D -- No --> F[Non-overlapping — keep separate]

    E --> G[Use for: Merge Intervals, Insert Interval]
    F --> H[Use for: Non-Overlapping — count removals]

    style E fill:#2d6a4f,color:#fff
    style F fill:#9b2226,color:#fff

Complexity Summary

Problem Time Space
Insert Interval O(n) O(n)
Merge Intervals O(n log n) O(n)
Non-Overlapping Intervals O(n log n) O(1)
Meeting Rooms O(n log n) O(1)
Meeting Rooms II O(n log n) O(n)
Meeting Rooms III O(n log n) O(n)
Min Interval per Query O((n+q) log n) O(n+q)

Study Order

  1. Meeting Rooms — basic overlap check
  2. Merge Intervals — core merge pattern
  3. Insert Interval — merge with binary search
  4. Non-Overlapping Intervals — greedy scheduling
  5. Meeting Rooms II — heap for resource counting
  6. Meeting Rooms III — two-heap advanced
  7. Minimum Interval per Query — offline + heap

Intervals

Core Intuition

Interval problems reduce to: sort by start (or end), then decide how to merge, count, or schedule. After sorting, you only ever need to compare the current interval with the last processed one (or the top of a heap).

  • Sort-then-scan: The foundational pattern. Sort by start; walk left to right; if current.start <= last.end they overlap — extend last.end = max(last.end, current.end). Used in merge_intervals and insert_interval.
  • Greedy by end time: For non_overlapping_intervals — sort by end, keep the interval finishing earliest, skip (count as removed) anything that conflicts. Minimises removals because an early-ending interval blocks the fewest future ones.
  • Sweep line: Count how many intervals are "active" at any point. Split each interval into a +1 event at start and a -1 event at end; walk events in order; running sum is the concurrent count. Two-pointer variant: sort starts and ends separately, advance the end pointer whenever a meeting has finished.
  • Heap-based (active set): Sort by start; maintain a min-heap of end times for in-progress intervals. If the earliest-ending interval finishes before the next one starts, reuse its slot. Heap size = answer. Used in meeting_rooms_ii and meeting_rooms_iii.
  • Offline query approach: For minimum_interval — sort intervals by start, sort queries by value (keeping original indices), sweep queries left to right pushing newly-eligible intervals onto a min-heap (by size), evicting expired ones from the top.

Java Idioms

// Sort by start time (standard for merge, insert, meeting rooms)
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);

// Sort by end time (non_overlapping_intervals greedy)
Arrays.sort(intervals, (a, b) -> a[1] - b[1]);

// Output size unknown: build list, convert at the end
List<int[]> res = new ArrayList<>();
// ... populate ...
return res.toArray(new int[0][]);

// Sweep line: encode start/end events in one array
int[][] events = new int[2 * n][2];
for (int i = 0; i < n; i++) {
    events[2 * i]     = new int[]{intervals[i][0],  1};  // start
    events[2 * i + 1] = new int[]{intervals[i][1], -1};  // end
}
Arrays.sort(events, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);

// Meeting Rooms II: min-heap of end times
PriorityQueue<Integer> endTimes = new PriorityQueue<>();

// Meeting Rooms III / minimum_interval: heap sorted by interval size
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
// store [size, end] so smallest interval surfaces first

// Merging end times: always take max (containment case)
int newEnd = Math.max(last[1], current[1]);

Problems

Problem Key Insight Tricky Part Common Mistakes Time Space
insert_interval (LC 57) Three phases: copy intervals ending before new one, merge all overlapping, copy remainder Overlap condition: existing.end >= new.start && existing.start <= new.end Off-by-one on overlap check; forgetting the case where new interval fits between two existing ones without overlapping either O(n) O(n)
merge_intervals (LC 56) Sort by start; extend last.end = max(last.end, curr.end) when curr.start <= last.end Must use max not just assign — one interval may be fully contained inside another Skipping max so a contained interval shrinks the merged end; not sorting first O(n log n) O(n)
non_overlapping_intervals (LC 435) Sort by end; greedily keep interval with earliest end; increment removal counter on conflict Count intervals removed, not kept; sort by end not start Sorting by start instead of end; returning count of kept intervals instead of removed O(n log n) O(1)
meeting_rooms (LC 252) Sort by start; any intervals[i].start < intervals[i-1].end means conflict Sort is mandatory before the linear scan Comparing without sorting first; using <= instead of < (adjacent meetings are fine) O(n log n) O(1)
meeting_rooms_ii (LC 253) Min-heap of end times; if heap[0] <= curr.start, pop and push new end (reuse room); else push (new room) Sweep-line alternative: sort starts and ends separately, two pointers — advance end pointer only when a meeting fully ends before next starts (start >= end, strict) Using <= in sweep line (makes adjacent meetings share a room when they shouldn't); forgetting heapreplace for the reuse case O(n log n) O(n)
meeting_rooms_iii (LC 2402) Two heaps: available (room numbers, min-heap), occupied ([end_time, room], min-heap); when none free, pull earliest-ending room Must track which room is used per meeting to count per-room assignments; ties broken by lowest room number (heap handles this if room number is second key) Using only one heap; not counting per-room usage; not initialising available with all room numbers 0..n-1 O((n+m) log n) O(n)
minimum_interval_to_include_each_query (LC 1851) Sort intervals by start; sort queries offline with original indices; sweep pushing [size, end] onto min-heap, evicting expired intervals Must remove from heap all intervals whose end < query before reading the top; use end - start + 1 for size Sorting intervals by size upfront (wrong — breaks the sweep); not saving original query index; integer overflow on size if using 32-bit arithmetic with large bounds O((n+q) log n) O(n+q)

Pattern Recognition Guide

Use this to pick the right approach when a new problem appears:

  1. Combine overlapping intervals into fewer intervals → sort by start, merge (merge_intervals pattern).
  2. Insert one interval into a sorted list → three-phase linear pass, no re-sort needed (insert_interval pattern).
  3. Remove minimum intervals to make list non-overlapping → sort by end, greedy keep (non_overlapping_intervals pattern).
  4. Can a single person/entity attend all events? → sort by start, check pairwise overlap (meeting_rooms pattern).
  5. How many parallel resources needed at peak? → min-heap of end times, heap size = answer (meeting_rooms_ii pattern). Use two heaps if you also need to track which resource (meeting_rooms_iii pattern).
  6. For each point/query, find the containing interval with some property (e.g. smallest)? → offline sort both, sweep with min-heap keyed on that property (minimum_interval pattern).

Key disambiguation: "remove minimum" sounds like counting — it's actually a greedy scheduling problem. "How many rooms" sounds like counting — it's actually a heap/sweep problem.

Algorithm Skeletons

Insert Interval

result = []
i, n = 0, len(intervals)
# Phase 1: intervals ending before new interval starts
while i < n and intervals[i][1] < new_interval[0]:
    result.append(intervals[i]); i += 1
# Phase 2: merge overlapping
while i < n and intervals[i][0] <= new_interval[1]:
    new_interval[0] = min(new_interval[0], intervals[i][0])
    new_interval[1] = max(new_interval[1], intervals[i][1])
    i += 1
result.append(new_interval)
# Phase 3: remainder
result.extend(intervals[i:])

Non-Overlapping Intervals (greedy)

intervals.sort(key=lambda x: x[1])  # sort by END
end, removed = intervals[0][1], 0
for start, e in intervals[1:]:
    if start < end:       # conflict: remove current (keep earlier-ending one)
        removed += 1
    else:
        end = e           # advance the boundary
return removed

Merge Intervals

intervals.sort(key=lambda x: x[0])
result = [intervals[0]]
for start, end in intervals[1:]:
    if start <= result[-1][1]:
        result[-1][1] = max(result[-1][1], end)
    else:
        result.append([start, end])

Meeting Rooms II (heap)

intervals.sort()
heap = []  # end times
for start, end in intervals:
    if heap and heap[0] <= start:
        heapq.heapreplace(heap, end)
    else:
        heapq.heappush(heap, end)
return len(heap)

Minimum Interval per Query

intervals.sort()
sorted_q = sorted(enumerate(queries), key=lambda x: x[1])
result = [-1] * len(queries)
heap, i = [], 0
for idx, q in sorted_q:
    while i < len(intervals) and intervals[i][0] <= q:
        s, e = intervals[i]
        heapq.heappush(heap, (e - s + 1, e))
        i += 1
    while heap and heap[0][1] < q:
        heapq.heappop(heap)
    if heap:
        result[idx] = heap[0][0]

General Edge Cases

  • Single interval: every problem degenerates trivially — nothing to merge, compare, or schedule. Test it anyway; index-out-of-bounds bugs live here.
  • No overlap, adjacent intervals: [1,2] and [2,3] touch but don't overlap. Merge Intervals: merge them (start <= last.end uses <=, so 2 <= 2 → merge). Meeting Rooms: they don't conflict (start < last.end uses strict <, so 2 < 2 is false → same room). Know which comparison each problem uses.
  • Complete containment: [1,10] fully contains [2,5]. The inner interval must not shrink the merged result — always max(last.end, curr.end), never just curr.end.
  • Insert before all existing: new interval ends before the first existing start — the three-phase insert just copies everything after the new interval; nothing gets merged.
  • Insert after all existing: new interval starts after the last existing end — same logic, nothing gets merged, new interval appended.
  • All intervals identical: meeting rooms → answer is n; merge → answer is 1 interval; non-overlapping → remove n-1.
  • Query falls outside all intervals (minimum_interval): heap is empty after eviction → result stays -1. Must not read heap[0] without checking if heap.
  • Integer overflow on interval size: end - start + 1 with large bounds (up to 10^7) fits in 32-bit int, but if you compute size as part of a sort key involving multiplication, overflow is possible. In Java, use (a, b) -> Integer.compare(a[0], b[0]) rather than subtraction when values approach Integer.MAX_VALUE.
# Problem LC # Difficulty Key Technique
1 Insert Interval 57 Medium Linear scan + merge
2 Merge Intervals 56 Medium Sort + merge
3 Non-Overlapping Intervals 435 Medium Greedy scheduling
4 Meeting Rooms 252 Easy Sort + check overlap
5 Meeting Rooms II 253 Medium Min-heap
6 Meeting Rooms III 2402 Hard Two heaps
7 Minimum Interval to Include Each Query 1851 Hard Sort + heap + offline queries
Insert Interval PythonJava
▼
from typing import List


class Solution:
    """
    ## 57. Insert Interval

    Given a list of non-overlapping intervals sorted by start time, insert a new interval
    and merge if necessary. Return the resulting list of non-overlapping intervals.

    ### Example
    ```text
    Input:  intervals = [[1,3],[6,9]], newInterval = [2,5]
    Output: [[1,5],[6,9]]

    Input:  intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
    Output: [[1,2],[3,10],[12,16]]
    ```

    ### Constraints
    - 0 <= intervals.length <= 10^4
    - intervals is sorted in ascending order by start
    - intervals[i].length == newInterval.length == 2
    - 0 <= intervals[i][0] <= intervals[i][1] <= 10^5
    """

    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        # Add all intervals ending before new interval starts
        # Merge all overlapping intervals with the new one
        # Add remaining intervals that start after the merged interval ends
        # O(n) time, O(n) space — linear scan and merge
        result = []
        i, n = 0, len(intervals)
        # Add all intervals that end before newInterval starts
        while i < n and intervals[i][1] < newInterval[0]:
            result.append(intervals[i])
            i += 1
        # Merge all overlapping intervals
        while i < n and intervals[i][0] <= newInterval[1]:
            newInterval[0] = min(newInterval[0], intervals[i][0])
            newInterval[1] = max(newInterval[1], intervals[i][1])
            i += 1
        result.append(newInterval)
        # Add remaining intervals
        result.extend(intervals[i:])
        return result


if __name__ == '__main__':
    s = Solution()
    assert s.insert([[1, 3], [6, 9]], [2, 5]) == [[1, 5], [6, 9]]
    assert s.insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]) == [[1, 2], [3, 10], [12, 16]]
    assert s.insert([], [5, 7]) == [[5, 7]]
    assert s.insert([[1, 5]], [2, 3]) == [[1, 5]]
    print("All tests passed.")
Meeting Rooms PythonJava
▼
from typing import List


class Solution:
    """
    ## 252. Meeting Rooms

    Given an array of meeting time intervals where intervals[i] = [start_i, end_i],
    return true if a person could attend all meetings (no two meetings overlap).

    ### Example
    ```text
    Input:  intervals = [[0,30],[5,10],[15,20]]
    Output: false

    Input:  intervals = [[7,10],[2,4]]
    Output: true
    ```

    ### Constraints
    - 0 <= intervals.length <= 10^4
    - intervals[i].length == 2
    - 0 <= start_i < end_i <= 10^6
    """

    def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
        # Sort by start; if any meeting starts before previous ends, conflict
        # O(n log n) time, O(1) space — sort by start and check adjacent overlap
        intervals.sort(key=lambda x: x[0])
        for i in range(1, len(intervals)):
            if intervals[i][0] < intervals[i - 1][1]:
                return False
        return True


if __name__ == '__main__':
    s = Solution()
    assert s.canAttendMeetings([[0, 30], [5, 10], [15, 20]]) == False
    assert s.canAttendMeetings([[7, 10], [2, 4]]) == True
    assert s.canAttendMeetings([]) == True
    assert s.canAttendMeetings([[1, 5], [5, 10]]) == True
    print("All tests passed.")
Meeting Rooms Ii PythonJava
▼
from typing import List
import heapq


class Solution:
    """
    ## 253. Meeting Rooms II

    Given an array of meeting time intervals, return the minimum number of conference rooms required.

    ### Example
    ```text
    Input:  intervals = [[0,30],[5,10],[15,20]]
    Output: 2

    Input:  intervals = [[7,10],[2,4]]
    Output: 1
    ```

    ### Constraints
    - 1 <= intervals.length <= 10^4
    - 0 <= start_i < end_i <= 10^6
    """

    def minMeetingRooms_heap(self, intervals: List[List[int]]) -> int:
        # O(n log n) time, O(n) space — sort + min heap of end times
        intervals.sort(key=lambda x: x[0])
        heap = []  # min-heap of end times
        for start, end in intervals:
            if heap and heap[0] <= start:
                heapq.heapreplace(heap, end)
            else:
                heapq.heappush(heap, end)
        return len(heap)

    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        # Min-heap of end times: if next meeting starts after earliest end, reuse room
        # Otherwise allocate a new room; heap size = rooms needed
        # O(n log n) time, O(n) space — chronological ordering with start/end events
        starts = sorted(s for s, _ in intervals)
        ends = sorted(e for _, e in intervals)
        rooms = end_ptr = 0
        for start in starts:
            if start < ends[end_ptr]:
                rooms += 1
            else:
                end_ptr += 1
        return rooms


if __name__ == '__main__':
    s = Solution()
    assert s.minMeetingRooms([[0, 30], [5, 10], [15, 20]]) == 2
    assert s.minMeetingRooms([[7, 10], [2, 4]]) == 1
    assert s.minMeetingRooms([[1, 5], [2, 6], [3, 7]]) == 3
    assert s.minMeetingRooms_heap([[0, 30], [5, 10], [15, 20]]) == 2
    print("All tests passed.")
Meeting Rooms Iii PythonJava
▼
from typing import List
import heapq


class Solution:
    """
    ## 2402. Meeting Rooms III

    You have n rooms numbered 0 to n-1. Meetings are given as [start, end] (half-open).
    Each meeting is assigned to the lowest-numbered available room. If no room is free,
    the meeting is delayed until the earliest room becomes free (duration preserved).
    Return the room that held the most meetings (lowest index on tie).

    ### Example
    ```text
    Input:  n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
    Output: 0

    Input:  n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]
    Output: 1
    ```

    ### Constraints
    - 1 <= n <= 100
    - 1 <= meetings.length <= 10^5
    - 0 <= start_i < end_i <= 5 * 10^5
    """

    def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
        # Two heaps: available rooms (min-heap of room indices) and busy rooms (end_time, room)
        # Free up rooms whose end_time <= current meeting start before assigning
        # If no room available, wait for earliest-ending room; track usage count per room
        # O(m log n) time, O(n) space — two heaps: available rooms and ongoing meetings
        meetings.sort()
        available = list(range(n))          # min-heap of free room indices
        ongoing = []                         # min-heap of (end_time, room_index)
        count = [0] * n

        for start, end in meetings:
            # Free up rooms that have finished
            while ongoing and ongoing[0][0] <= start:
                _, room = heapq.heappop(ongoing)
                heapq.heappush(available, room)

            if available:
                room = heapq.heappop(available)
                heapq.heappush(ongoing, (end, room))
            else:
                # Delay: use the room that finishes earliest
                finish, room = heapq.heappop(ongoing)
                heapq.heappush(ongoing, (finish + (end - start), room))

            count[room] += 1

        return count.index(max(count))


if __name__ == '__main__':
    s = Solution()
    assert s.mostBooked(2, [[0, 10], [1, 5], [2, 7], [3, 4]]) == 0
    assert s.mostBooked(3, [[1, 20], [2, 10], [3, 5], [4, 9], [6, 8]]) == 1
    assert s.mostBooked(1, [[0, 1], [1, 2], [2, 3]]) == 0
    print("All tests passed.")
Merge Intervals PythonJava
▼
from typing import List


class Solution:
    """
    ## 56. Merge Intervals

    Given an array of intervals, merge all overlapping intervals and return an array
    of the non-overlapping intervals that cover all the intervals in the input.

    ### Example
    ```text
    Input:  intervals = [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]

    Input:  intervals = [[1,4],[4,5]]
    Output: [[1,5]]
    ```

    ### Constraints
    - 1 <= intervals.length <= 10^4
    - intervals[i].length == 2
    - 0 <= intervals[i][0] <= intervals[i][1] <= 10^4
    """

    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        # Sort by start time; merge current with next if they overlap
        # Two intervals overlap if next.start <= current.end
        # O(n log n) time, O(n) space — sort by start then merge
        intervals.sort(key=lambda x: x[0])
        result = [intervals[0]]
        for start, end in intervals[1:]:
            if start <= result[-1][1]:
                result[-1][1] = max(result[-1][1], end)
            else:
                result.append([start, end])
        return result


if __name__ == '__main__':
    s = Solution()
    assert s.merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
    assert s.merge([[1, 4], [4, 5]]) == [[1, 5]]
    assert s.merge([[1, 4], [0, 4]]) == [[0, 4]]
    assert s.merge([[1, 4], [2, 3]]) == [[1, 4]]
    print("All tests passed.")
Minimum Interval To Include Each Query PythonJava
▼
from typing import List
import heapq


class Solution:
    """
    ## 1851. Minimum Interval to Include Each Query

    You are given a 2D integer array intervals and an integer array queries.
    For each query, find the size (end - start + 1) of the smallest interval containing
    the query point. Return -1 if no such interval exists.

    ### Example
    ```text
    Input:  intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
    Output: [3,3,1,4]
    (query 2: [2,4] size 3; query 3: [2,4] size 3; query 4: [4,4] size 1; query 5: [3,6] size 4)

    Input:  intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
    Output: [2,-1,4,6]
    ```

    ### Constraints
    - 1 <= intervals.length <= 10^5
    - 1 <= queries.length <= 10^5
    - 1 <= intervals[i][0] <= intervals[i][1] <= 10^7
    - 1 <= queries[i] <= 10^7
    """

    def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
        # Sort intervals by length; sort queries with original indices
        # Sweep queries in order; add intervals that start <= query to a min-heap by size
        # Pop intervals from heap that end < query; top of heap is the answer
        # O((n + q) log n) time, O(n + q) space — sort intervals and queries, sweep with min heap
        intervals.sort()
        sorted_queries = sorted(enumerate(queries), key=lambda x: x[1])
        result = [-1] * len(queries)
        heap = []  # (size, end) — min heap by interval size
        i = 0

        for idx, q in sorted_queries:
            # Push all intervals whose start <= q
            while i < len(intervals) and intervals[i][0] <= q:
                start, end = intervals[i]
                heapq.heappush(heap, (end - start + 1, end))
                i += 1
            # Remove intervals that have ended before q
            while heap and heap[0][1] < q:
                heapq.heappop(heap)
            if heap:
                result[idx] = heap[0][0]

        return result


if __name__ == '__main__':
    s = Solution()
    assert s.minInterval([[1, 4], [2, 4], [3, 6], [4, 4]], [2, 3, 4, 5]) == [3, 3, 1, 4]
    assert s.minInterval([[2, 3], [2, 5], [1, 8], [20, 25]], [2, 19, 5, 22]) == [2, -1, 4, 6]
    print("All tests passed.")
Non Overlapping Intervals PythonJava
▼
from typing import List


class Solution:
    """
    ## 435. Non-overlapping Intervals

    Given an array of intervals, return the minimum number of intervals you need to remove
    to make the rest of the intervals non-overlapping.

    ### Example
    ```text
    Input:  intervals = [[1,2],[2,3],[3,4],[1,3]]
    Output: 1  (remove [1,3])

    Input:  intervals = [[1,2],[1,2],[1,2]]
    Output: 2

    Input:  intervals = [[1,2],[2,3]]
    Output: 0
    ```

    ### Constraints
    - 1 <= intervals.length <= 10^5
    - intervals[i].length == 2
    - -5 * 10^4 <= intervals[i][0] < intervals[i][1] <= 5 * 10^4
    """

    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        # Sort by end time; greedily keep intervals with earliest end
        # Count intervals that must be removed (overlap with last kept)
        # O(n log n) time, O(1) space — sort by end, greedily keep non-overlapping
        intervals.sort(key=lambda x: x[1])
        removed = 0
        prev_end = float('-inf')
        for start, end in intervals:
            if start >= prev_end:
                prev_end = end
            else:
                removed += 1
        return removed


if __name__ == '__main__':
    s = Solution()
    assert s.eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
    assert s.eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]]) == 2
    assert s.eraseOverlapIntervals([[1, 2], [2, 3]]) == 0
    print("All tests passed.")

Merge Intervals

Sort by start, merge overlapping intervals greedily

012345678910111213141516171819[1,3][2,6][8,10][15,18]merged:
Intervals sorted by start. Press "Next Step" to merge.
Speed3x