Question

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

This is anintervals question.

Idea

  • The key is to sort the intervals based on the starting value
  • We pre-emptively add the first interval to res
  • Now the goal is to determine whether or not we need to expend the last added thing in res
    • We do this by checking to see if our current start value ≤ the last added interval in res
      • If so, we change the end value to the max of our current end, or the pre-existing end
    • Otherwise, just add the current interval to res
  • Return res

Solution