JCSU Unit 5 Problem Set 1 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
[start, end]
where start <= end
.HAPPY CASE Input: intervals = [ [1, 3], [2, 4], [5, 7], [6, 8] ] Output: [ [1, 4], [5, 8] ] Explanation: The intervals [1, 3] and [2, 4] overlap and are merged into [1, 4]. The intervals [5, 7] and [6, 8] overlap and are merged into [5, 8].
EDGE CASE Input: intervals = [] Output: [] Explanation: An empty list results in an empty output.
EDGE CASE Input: intervals = [ [1, 2], [2, 3] ] Output: [ [1, 3] ] Explanation: The intervals [1, 2] and [2, 3] are contiguous and merged into [1, 3].
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For interval merging problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Sort the intervals by their starting point. Iterate through the intervals and compare each interval with the last merged interval. If they overlap, merge them by extending the end of the last merged interval. Otherwise, add the current interval as a new interval.
intervals
list is empty. If so, return an empty list.intervals
by their starting points.merged
list with the first interval.intervals
starting from the second interval:
merged
list.merged
list.Implement the code to solve the algorithm.
def merge_intervals(intervals):
if not intervals: # Check if the input list is empty
return []
# Sort intervals by their starting point
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]] # Initialize the merged list with the first interval
for i in range(1, len(intervals)):
current = intervals[i]
last_merged = merged[-1] # Get the last interval in the merged list
if current[0] <= last_merged[1]: # Check if the intervals overlap
# Merge the intervals by updating the end of the last interval
last_merged[1] = max(last_merged[1], current[1])
else:
merged.append(current) # Add the current interval as a new interval
return merged # Return the merged list of intervals
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
Example 2:
Example 3:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n is the number of intervals.