Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Merge Intervals | Leetcode 56 | Brute Force and Optimal
    Data Structures & Algorithms

    Merge Intervals | Leetcode 56 | Brute Force and Optimal

    Anirudh KhuranaBy Anirudh Khurana7 July 2025Updated:16 November 2026No Comments8 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to merge intervals on leetcode
    Share
    Facebook Twitter LinkedIn Pinterest Email

    If you want to master array problems, “Merge Intervals” is a must-know question! In this blog, we’ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with comments, dry runs, and clear explanations.

    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.

    Here’s the [Problem Link] to begin with.

    Example 1:

    Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]
    Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

    Example 2:

    Input: intervals = [[1,4],[4,5]]
    Output: [[1,5]]
    Explanation: Intervals [1,4] and [4,5] are considered overlapping.

    Constraints:

    • 1 <= intervals.length <= 104
    • intervals[i].length == 2
    • 0 <= starti <= endi <= 104
    Contents:
    • Brute Force Solution
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Dry Run
      • Time and Space Complexity
      • Conclusion
    • Optimal Solution
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Dry Run
      • Time and Space Complexity
      • Conclusion
    • Final Thoughts

    Interactive Visualizer: Sort, Then Merge

    Choose an example or type your own intervals, then press Next to follow the optimal solution. The orange bar is the interval being checked, and the green bars on the Merged row are the answer so far (blue when it was just extended).



    Brute Force Solution

    Intuition and Approach

    Let’s solve the problem step by step in the simplest way:

    1. Sort the Intervals:
      Sorting helps us line up all intervals so that overlapping intervals are next to each other.
    2. Check Each Interval:
      For every interval, try to merge it with all future intervals that overlap with it.
    3. Skip Already Merged Intervals:
      If an interval is already covered by a previous merge, skip it.
    4. Why does this work?
      We check every possible overlap and merge accordingly. This ensures all intervals are merged correctly, but it’s not the most efficient.

    Code Implementation

    from typing import List
    
    class Solution:
        def merge(self, intervals: List[List[int]]) -> List[List[int]]:
            n = len(intervals)
            intervals.sort()                         # sort intervals by start time
            ans = []
            for i in range(n):
                start, end = intervals[i][0], intervals[i][1]   # current interval
    
                # skip if current interval is already merged
                if len(ans) != 0 and end <= ans[-1][1]:
                    continue
    
                # try to merge with future overlapping intervals
                for j in range(i + 1, n):
                    if intervals[j][0] <= end:                # overlap found
                        end = max(end, intervals[j][1])       # extend end to the farthest overlap
                    else:
                        break                                 # stop if no overlap
                ans.append([start, end])                      # add merged interval to answer
            return ans
    Python
    class Solution {
        public int[][] merge(int[][] intervals) {
            int n = intervals.length;
            Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
                                                          : Integer.compare(a[1], b[1])); // sort by start time
            List<int[]> ans = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                int start = intervals[i][0], end = intervals[i][1]; // current interval
    
                // skip if current interval is already merged
                if (!ans.isEmpty() && end <= ans.get(ans.size() - 1)[1]) continue;
    
                // try to merge with future overlapping intervals
                for (int j = i + 1; j < n; j++) {
                    if (intervals[j][0] <= end) {            // overlap found
                        end = Math.max(end, intervals[j][1]); // extend end to the farthest overlap
                    } else {
                        break;                               // stop if no overlap
                    }
                }
                ans.add(new int[]{start, end});              // add merged interval to answer
            }
            return ans.toArray(new int[ans.size()][]);
        }
    }
    class Solution {
    public:
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            int n = intervals.size();
            sort(intervals.begin(), intervals.end()); // sort intervals by start time
            vector<vector<int>> ans;
            for (int i = 0; i < n; i++) {
                int start = intervals[i][0], end = intervals[i][1]; // current interval
    
                // skip if current interval is already merged
                if (!ans.empty() && end <= ans.back()[1]) continue;
    
                // try to merge with future overlapping intervals
                for (int j = i + 1; j < n; j++) {
                    if (intervals[j][0] <= end) {       // overlap found
                        end = max(end, intervals[j][1]); // extend end to the farthest overlap
                    } else {
                        break;                          // stop if no overlap
                    }
                }
                ans.push_back({start, end});            // add merged interval to answer
            }
            return ans;
        }
    };

    Code Explanation

    • First, we sort the intervals to make overlapping intervals adjacent.
    • For each interval, we check if it’s already merged; if so, we skip it.
    • Then, we look ahead to merge all intervals that overlap with the current one.
    • We add the merged interval to our answer list.

    Dry Run

    Input:
    intervals = [[1,3],[2,6],[8,10],[15,18]]

    • After sorting: [[1,3],[2,6],[8,10],[15,18]]
    • i = 0: start with [1,3]. [2,6] overlaps (2 ≤ 3), so merge to [1,6]. [8,10] does not overlap (8 > 6), so stop and add [1,6].
    • i = 1: [2,6] ends at 6, which is not beyond the last merged end 6, so it was already merged. Skip it.
    • i = 2: start with [8,10]. [15,18] does not overlap, so add [8,10].
    • i = 3: start with [15,18]. There are no more intervals, so add [15,18].
    • Final output: [[1,6],[8,10],[15,18]]

    Time and Space Complexity

    • Time Complexity: O(N^2)
      For each interval, we may check all future intervals.
    • Space Complexity: O(N)
      For the answer list.

    Conclusion

    The brute force approach is easy to understand but slow for large lists. It’s good for learning the basics of the problem.


    Optimal Solution

    Intuition and Approach

    We can solve this problem much faster by merging intervals as we go:

    1. Sort the Intervals:
      Sorting puts overlapping intervals next to each other.
    2. Merge on the Go:
      As we go through each interval, check if it overlaps with the last interval in our answer list. If it does, merge them. If not, add it as a new interval.
    3. Why does this work?
      After sorting, all overlaps are adjacent, so we only need to look at the last merged interval.

    Code Implementation

    from typing import List
    
    class Solution:
        def merge(self, intervals: List[List[int]]) -> List[List[int]]:
            n = len(intervals)
            intervals.sort()                              # sort intervals by start time
            ans = []
            for i in range(n):
                # if ans is empty or no overlap, add interval
                if len(ans) == 0 or intervals[i][0] > ans[-1][1]:
                    ans.append(intervals[i])
                else:
                    # merge with the last interval in ans
                    ans[-1][1] = max(ans[-1][1], intervals[i][1])
            return ans
    Python
    class Solution {
        public int[][] merge(int[][] intervals) {
            int n = intervals.length;
            Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
                                                          : Integer.compare(a[1], b[1])); // sort by start time
            List<int[]> ans = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                // if ans is empty or no overlap, add interval
                if (ans.isEmpty() || intervals[i][0] > ans.get(ans.size() - 1)[1]) {
                    ans.add(intervals[i]);
                } else {
                    // merge with the last interval in ans
                    int[] last = ans.get(ans.size() - 1);
                    last[1] = Math.max(last[1], intervals[i][1]);
                }
            }
            return ans.toArray(new int[ans.size()][]);
        }
    }
    class Solution {
    public:
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            int n = intervals.size();
            sort(intervals.begin(), intervals.end()); // sort intervals by start time
            vector<vector<int>> ans;
            for (int i = 0; i < n; i++) {
                // if ans is empty or no overlap, add interval
                if (ans.empty() || intervals[i][0] > ans.back()[1]) {
                    ans.push_back(intervals[i]);
                } else {
                    // merge with the last interval in ans
                    ans.back()[1] = max(ans.back()[1], intervals[i][1]);
                }
            }
            return ans;
        }
    };

    Code Explanation

    • We sort the intervals.
    • For each interval, if it doesn’t overlap with the last interval in the answer, we add it.
    • If it does overlap, we merge it with the last interval by updating the end value.

    Dry Run

    Input:
    intervals = [[1,3],[2,6],[8,10],[15,18]]

    • After sorting: [[1,3],[2,6],[8,10],[15,18]]
    • [1,3]: the answer is empty, so add it → [[1,3]]
    • [2,6]: overlaps with [1,3] (2 ≤ 3), merge to [1,6] → [[1,6]]
    • [8,10]: no overlap (8 > 6), add → [[1,6],[8,10]]
    • [15,18]: no overlap (15 > 10), add → [[1,6],[8,10],[15,18]]

    Time and Space Complexity

    • Time Complexity: O(N log N)
      Sorting dominates; merging is O(N).
    • Space Complexity: O(N)
      For the answer list.

    Conclusion

    The optimal solution is efficient and elegant. It’s the best approach for interviews and large datasets.

    Final Thoughts

    The “Merge Intervals” problem is a great example of how sorting and merging can simplify complex problems. Start with brute force to understand the basics, then use the optimal solution for best performance.

    Frequently Asked Questions

    What is the Merge Intervals problem?

    Given a list of intervals [start, end], merge every group of overlapping intervals and return the non-overlapping intervals that cover the same ranges. For [[1,3],[2,6],[8,10],[15,18]] the answer is [[1,6],[8,10],[15,18]].

    Why do we sort the intervals first?

    After sorting by start time, any interval that overlaps the merged ones must overlap the last merged interval. That means one comparison per interval is enough, instead of comparing every pair.

    Do touching intervals like [1,4] and [4,5] merge?

    Yes. In LeetCode 56 two intervals overlap when the next start is less than or equal to the current end, so [1,4] and [4,5] merge into [1,5].

    What is the time and space complexity of Merge Intervals?

    The optimal solution takes O(n log n) time because of the sort; the merge pass itself is O(n). It uses O(n) space for the output list, plus whatever space the sort needs.

    Where is Merge Intervals used in real life?

    The same idea is used to combine overlapping meeting slots in calendars, merge time ranges in logs, and join overlapping ranges in booking systems. Related problems include Insert Interval (LeetCode 57) and Non-overlapping Intervals (LeetCode 435).


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.

    Array Hard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleLargest Subarray with 0 Sum – GeeksforGeeks Solution Explained
    Next Article Merge Without Extra Space – GeeksforGeeks Solution Explained
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (6)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (2)
    Recent Posts

    Normalization in DBMS: 1NF, 2NF and 3NF With SQL Examples

    25 November 2026

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.