Taro Logo

Non-overlapping Intervals

#125 Most AskedMedium
Topics:
ArraysGreedy Algorithms

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping.

Example 1:

Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.

Example 2:

Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.

Example 3:

Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

Constraints:

  • 1 <= intervals.length <= 105
  • intervals[i].length == 2
  • -5 * 104 <= starti < endi <= 5 * 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the start and end times of the intervals be negative numbers, or are they strictly non-negative?
  2. How should we handle intervals that touch exactly at endpoints, such as [1, 2] and [2, 3]? Do they count as overlapping?
  3. Are the input intervals guaranteed to be sorted by their start or end times, or can they be in completely arbitrary order?
  4. What should the function return if the input array is empty or contains only a single interval?
  5. Can an interval have a start time greater than or equal to its end time (e.g., [3, 1] or [2, 2]), or is `start < end` always guaranteed?

Brute Force Solution

Approach

Imagine you have a calendar full of meetings that overlap with each other, and you want to remove the fewest meetings possible so that everyone can attend their meetings without any time conflicts. The brute force approach involves testing every single combination of removing meetings to see which choices successfully eliminate all overlaps.

Here's how the algorithm would work step-by-step:

  1. Start by listing every possible combination of meetings you could choose to remove, from removing just a single meeting to removing multiple meetings at once.
  2. Take the first combination of meetings you decided to remove and pretend those meetings are canceled from the calendar.
  3. Look at the remaining meetings that are still on the calendar and check them one by one to see if any of their scheduled times clash with each other.
  4. If you still find at least one time conflict among the remaining meetings, cross that removal combination off your list because it did not work.
  5. If you check all the remaining meetings and find zero overlaps, then that combination of removals is a successful solution.
  6. Repeat this testing process for every single combination of meeting removals you generated at the very beginning.
  7. Finally, look at all the successful combinations you found and pick the one that required you to remove the smallest number of meetings.

Code Implementation

from itertools import combinations


def erase_overlap_intervals(intervals):
    total_intervals = len(intervals)
    
    # Iterate through all possible removal sizes from smallest to largest to find the minimum removals
    for removal_count in range(total_intervals + 1):
        for removed_indices in combinations(range(total_intervals), removal_count):
            remaining_meetings = [intervals[index] for index in range(total_intervals) if index not in removed_indices]
            remaining_meetings.sort(key=lambda meeting: meeting[0])
            
            has_conflict = False
            
            # Check each adjacent pair in the remaining meetings to detect any time overlaps
            for current_index in range(len(remaining_meetings) - 1):
                if remaining_meetings[current_index][1] > remaining_meetings[current_index + 1][0]:
                    has_conflict = True
                    break
            
            # Stop searching immediately once we find a valid subset because we started from the smallest removal count
            if not has_conflict:
                return removal_count
                
    return 0

Big(O) Analysis

Time Complexity
O(2^n * n) – For an input of n meetings, the brute force approach generates all possible subsets of removals, which results in 2^n combinations to test. For each of these combinations, we iterate through the remaining meetings to check for any time conflicts, taking up to n steps per combination. Multiplying these together leads to approximately (2^n) * n operations, which simplifies to O(2^n * n).
Space Complexity
O(2^n) – To execute the brute force approach, the algorithm must generate every possible combination of meeting removals, resulting in a power set of size 2 to the power of N where N is the number of meetings. Storing this list of combinations requires an auxiliary structure that grows exponentially with the input size N. Additionally, the algorithm uses temporary memory for variables to track the current combination being tested and to check for overlaps among the remaining meetings. Combining the exponential storage for all combinations with the recursion or iteration stack frames yields a total auxiliary space complexity of O(2^n).

Optimal Solution

Approach

Instead of testing every possible combination of schedules, we can use a greedy strategy to maximize the number of meetings we keep. By always picking the meeting that finishes the earliest, we leave as much room as possible for future meetings.

Here's how the algorithm would work step-by-step:

  1. Gather all the meeting schedules and sort them so that the ones ending the earliest come first.
  2. Start by looking at the first meeting on the sorted list and assume we are keeping it.
  3. Move on to the next meeting and check if it starts before the meeting we just kept finishes.
  4. If the new meeting clashes by starting too early, we must remove it to prevent an overlap, and count it as one removal.
  5. If the new meeting starts at or after the previous one finishes, there is no clash, so we keep it and update our current focus to this new meeting.
  6. Repeat this checking process for every meeting on the list from start to finish.
  7. At the end, the total count of removed meetings will be as small as possible, leaving the maximum number of non-overlapping meetings.

Code Implementation

def erase_overlap_intervals(meeting_intervals):
    if not meeting_intervals:
        return 0

    # Sorting by end time ensures we leave maximum room for future meetings.
    sorted_meetings = sorted(meeting_intervals, key=lambda interval: interval[1])

    removed_meetings_count = 0
    last_kept_end_time = sorted_meetings[0][1]

    for current_meeting in sorted_meetings[1:]:
        current_start_time = current_meeting[0]
        current_end_time = current_meeting[1]

        # Overlapping meetings must be removed to prevent schedule clashes.
        if current_start_time < last_kept_end_time:
            removed_meetings_count += 1
        else:
            # Keeping non-overlapping meetings updates our reference end time.
            last_kept_end_time = current_end_time

    return removed_meetings_count

Big(O) Analysis

Time Complexity
O(n log n) – The time complexity is driven by sorting the n meeting intervals based on their end times, which takes O(n log n) time. Afterward, we iterate through the sorted list of n meetings exactly once in a single linear pass to check for overlaps and make our greedy decisions, which takes O(n) time. Combining these steps, the sorting dominates the runtime, so the total operations simplify to O(n log n).
Space Complexity
O(n) or O(log n) – The space complexity is determined by the sorting step in the algorithm, where N represents the total number of meetings. Depending on the specific sorting algorithm used by the underlying language runtime, storing the sorted elements or the internal recursion stack frames for sorting requires auxiliary space proportional to O(log n) for in-place sorting or up to O(n) if a new collection is generated. Beyond this sorting overhead, the greedy selection process only maintains a few primitive tracking variables to store the previous meeting's end time and the removal count. Therefore, the total extra memory used beyond the input itself is dominated by the sorting operation, resulting in an overall auxiliary space complexity of O(n) in the worst case.

Edge Cases

Empty interval array
How to Handle:
Return zero immediately as an empty set requires zero removals to be non-overlapping.
Single interval array
How to Handle:
Return zero because an array with only one interval cannot have any overlaps.
Intervals that touch strictly at endpoints such as one to two and two to three
How to Handle:
The problem statement defines touching endpoints as overlapping, so our algorithm correctly identifies these as conflicts and removes one.
Completely identical intervals
How to Handle:
Sorting by end time and tracking the last valid end time ensures duplicates are treated as overlapping and correctly removed.
Intervals with negative start and end times
How to Handle:
Standard numerical comparison handles negative numbers correctly during sorting without requiring coordinate shifts.
Maximum possible number of intervals up to constraint limits
How to Handle:
An O(n log n) greedy approach based on sorting ensures the solution executes efficiently well within time limits.
Completely disjoint intervals already non-overlapping
How to Handle:
The greedy tracker will continuously update the end boundary without ever triggering a removal count increment, returning zero.
Extremely large coordinate values approaching integer limits
How to Handle:
Using standard 32-bit or 64-bit integer types prevents overflow since we only compare values rather than performing arithmetic.
0/245 completed