Introduction
In our last lesson, we explored monotonic stacks and queues, specialized data structures that enable linear-time solutions for problems like "Next Greater Element" and "Sliding Window Maximum." We saw how maintaining a strict order within the data structure allows for efficient, amortized operations.
Today, we shift our focus to a different but equally fundamental algorithmic pattern: interval merging. This pattern is crucial for problems involving overlapping ranges, which frequently appear in interviews and have direct applications in areas like calendar scheduling, resource allocation, and geometric data processing.
Your goal in this lesson is to master the core technique for handling such problems: sorting the intervals and then applying a single linear scan to merge them. We will tackle the two most common variants: "Merge Intervals" and "Insert Interval." Given your background, we'll pay special attention to the underlying logic, complexity trade-offs, and how to articulate a robust solution at a Staff-level interview.
The Interval Merging Pattern
An interval is simply a pair of numbers [start, end]. Two intervals [a, b] and [c, d] are said to overlap if they have at least one point in common. The core challenge in interval problems is to efficiently identify and consolidate these overlapping segments.

A naive approach might involve comparing every interval with every other interval, an process. The key insight of the interval merging pattern is that if we sort the intervals by their start times, any potential overlaps will only occur between an interval and the ones immediately following it. This transforms the problem into one that can be solved with a single linear scan after the initial sort.
To begin, let's explore the fundamental relationships that can exist between any two intervals.
This video from Destination FAANG provides a great visual introduction to the six possible ways two intervals can relate to each other, setting the stage for understanding overlap conditions.
Watch the first part of the video, from 00:00 to 04:28. Focus on visualizing the different overlap scenarios. This will help you build a strong mental model for the conditions we'll use in our algorithm.
Canonical Problem: Merge Intervals (LeetCode 56)
This is the quintessential problem for this pattern. You are given an array of intervals in an arbitrary order, and you must return a new array of non-overlapping intervals.
The core strategy is to sort and then scan. This approach is highly efficient and demonstrates a structured way to solve the problem.
56. Merge Intervals - In-Depth Explanation
This article from AlgoMonster succinctly explains why sorting is the critical first step. It frames the problem in a way that aligns well with an interview discussion.
Read the 'Intuition' section. Pay close attention to the explanation of how sorting changes the problem from a complex, global comparison task into a simple, local one where you only need to look at adjacent intervals.
With the intuition for sorting established, let's see how the full algorithm works.
The Algorithm
- Sort: Sort the input array of intervals based on their start times. This is the most crucial step and has a time complexity of .
- Initialize: Create a result list and add the first sorted interval to it. This will be our initial "merged" interval.
- Iterate and Merge: Loop through the remaining sorted intervals, starting from the second one. For each
current_interval, compare it with thelast_merged_intervalin your result list.- Overlap Condition:
current_interval.start <= last_merged_interval.end- If they overlap, merge them by updating the end of the
last_merged_interval:last_merged_interval.end = max(last_merged_interval.end, current_interval.end). We usemaxto handle cases where one interval is completely contained within another (e.g., merging[1, 10]with[2, 5]).
- If they overlap, merge them by updating the end of the
- No Overlap:
current_interval.start > last_merged_interval.end- If there is no overlap, the
last_merged_intervalis complete. Append thecurrent_intervalto the result list as the newlast_merged_interval.
- If there is no overlap, the
- Overlap Condition:
- Return: The result list now contains the final set of merged, non-overlapping intervals.
The following video provides a detailed, step-by-step walkthrough of this exact process.
Let's watch a full walkthrough of the 'Merge Intervals' problem. This will solidify the algorithm we just outlined.
Watch from 04:28 to 15:48. This section covers the problem from start to finish, including: Why unsorted input is difficult to handle. A clear visualization of the merging logic after sorting. The final complexity analysis.
Go Implementation and Staff-Level Discussion
Here is a clean, idiomatic Go implementation of the "Merge Intervals" solution. Note the use of sort.Slice for sorting and how the result slice is built up.
import "sort"
import "math"
func merge(intervals [][]int) [][]int {
if len(intervals) <= 1 {
return intervals
}
// 1. Sort the intervals based on their start times.
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
// 2. Initialize the result with the first interval.
// We will modify the last element of this slice in-place or append a new one.
merged := [][]int{intervals[0]}
// 3. Iterate through the rest of the intervals.
for i := 1; i < len(intervals); i++ {
currentInterval := intervals[i]
lastMerged := merged[len(merged)-1]
// Check for overlap
if currentInterval[0] <= lastMerged[1] {
// Overlap exists, merge them by updating the end of the last merged interval.
// Note: Go slices are reference types, but the integers within them are not.
// To modify the slice in `merged`, we need to access it by index.
merged[len(merged)-1][1] = int(math.Max(float64(lastMerged[1]), float64(currentInterval[1])))
} else {
// No overlap, add the current interval as a new merged interval.
merged = append(merged, currentInterval)
}
}
return merged
}
For a Staff-level interview, you're expected to go beyond just the code. You should be able to lead a discussion on edge cases, trade-offs, and potential pitfalls.
56. Merge Intervals - In-Depth Explanation
To round out your understanding, let's review common mistakes and edge cases. Being aware of these demonstrates experience and thoroughness.
Read the 'Common Pitfalls' section. For each point, consider how you would proactively address it in an interview. For example: Start by asking about constraints: 'Can the input be empty?' Explicitly state the overlap condition: 'We merge if the start of the new interval is less than or equal to the end of our current merged interval.' Justify the use of max: 'We take the max of the end-points to correctly handle fully contained intervals.'
A Common Variation: "Insert Interval" (LeetCode 57)
In this variation, you are given a list of already sorted, non-overlapping intervals and a new interval. The task is to insert the new interval into the list, merging if necessary.
Since the initial list is sorted, we can solve this in a single pass without an initial sort, leading to a more efficient solution.
The logic naturally breaks down into three phases:
- Before: Add all intervals from the original list that end before the new interval starts. They do not overlap and are unaffected.
- During (Merge): Once you find an interval that could overlap with the new interval, start a merging process. Iterate through all subsequent intervals that overlap with the (potentially expanding) new interval, merging them into a single
merged_interval. - After: Add the final
merged_intervalto the results, and then add all remaining intervals from the original list, which are guaranteed not to overlap.
This process is demonstrated clearly in the next segment of the video resource.
Let's see how the 'Insert Interval' variation is solved. The logic is a great example of handling different states in a single pass.
Watch from 19:06 to 26:53. Focus on how the algorithm moves through the three phases: adding initial non-overlapping intervals, performing the merge, and then adding the final non-overlapping intervals. Also, note the brief mention of a binary search-based approach, which is an excellent topic for a deep-dive discussion in a Staff+ interview.
Conclusion
Today you've mastered the interval merging pattern, a technique that relies on the powerful combination of sorting and linear scanning.
Key Takeaways:
- Sort First: Sorting intervals by their start time is the key that unlocks an efficient, linear-scan solution. It transforms a global
N-to-Ncomparison problem into a local one. - Merge Logic: The core of the merge is comparing the current interval's start with the previous merged interval's end. The merge operation itself involves updating the end to the maximum of the two interval ends.
- Complexity: The dominant factor for unsorted input is the
O(N log N)sort. The subsequent scan isO(N). For pre-sorted input (as in "Insert Interval"), the entire process isO(N). - Staff-Level Articulation: Be prepared to discuss why sorting works, the importance of handling edge cases like touching and contained intervals, and the time/space complexity trade-offs of your implementation choices (e.g., sorting in-place vs. creating a copy).
In our next lesson, we will build upon these ideas by looking at the sweep line algorithm. This is a more advanced technique that treats the start and end points of intervals as events on a timeline, allowing us to solve even more complex problems like "Meeting Rooms II" and "The Skyline Problem."