AlgoMaster Logo

Non-overlapping Intervals

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

The initial approach involves checking each pair of intervals to determine if they overlap. If an overlap is detected, remove one of the intervals and continue. This method, while straightforward, is not efficient, especially for large inputs, as it involves comparing each interval with every other interval.

Steps:

  1. Sort the intervals based on the starting point.
  2. Use two nested loops. The outer loop picks an interval, and the inner loop checks for overlaps with subsequent intervals.
  3. If an overlap is found, increment a counter to indicate a removal.
  4. Remove the interval that ends later to increase the chance of allowing future intervals to fit without overlap.

Code:

2. Optimized Greedy Approach

Intuition:

An improved approach leverages a greedy algorithm. By sorting intervals by their end time and then iterating through them, we can quickly identify and count needs for removal, aiming to minimize the number of intervals removed while maximizing the number of non-overlapping intervals.

Steps:

  1. Sort the intervals by the end time to efficiently find the optimal position to 'cut' the intervals.
  2. Initialize a counter for removals and set a variable for the end of the last added interval.
  3. Traverse the sorted intervals and check if the current interval overlaps with the last non-overlapping interval.
  4. If overlapped, increment the removal counter; otherwise, update the end point to the current interval’s end time.

Code: