TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
[starti, endi]
.Q: What is the expected output of the function?
Q: How should intervals be merged?
Q: What should the function return if the input array is empty?
The function merge_intervals() should take a list of intervals and return a new list where all overlapping intervals are merged. Overlapping intervals are defined as intervals where one interval starts before another ends.
HAPPY CASE
Input: [[1, 3], [2, 6], [8, 10], [15, 18]]
Expected Output: [[1, 6], [8, 10], [15, 18]]
EDGE CASE
Input: [[1, 4], [4, 5]]
Expected Output: [[1, 5]]
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Sort the intervals by their starting points, then iterate through them to merge overlapping intervals.
1. If the intervals list is empty, return an empty list.
2. Sort the intervals based on the starting point using a lambda function.
3. Initialize a list `merged` and add the first interval.
4. For each subsequent interval:
a. Compare the current interval with the last merged interval.
b. If they overlap (i.e., the start of the current interval is less than or equal to the end of the last merged interval):
- Merge them by updating the end of the last merged interval.
c. If they do not overlap:
- Append the current interval to the `merged` list.
5. Return the `merged` list.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def merge_intervals(intervals):
if not intervals:
return []
# Sort intervals by the starting point
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]: # Overlapping intervals
last[1] = max(last[1], current[1])
else:
merged.append(current)
return merged