{"id":522,"date":"2025-07-07T18:45:47","date_gmt":"2025-07-07T13:15:47","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=522"},"modified":"2025-07-07T18:45:48","modified_gmt":"2025-07-07T13:15:48","slug":"merge-intervals","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/merge-intervals\/","title":{"rendered":"Merge Intervals | Leetcode 56 | Brute Force and Optimal"},"content":{"rendered":"\n<p>If you want to master array problems, &#8220;Merge Intervals&#8221; is a must-know question! In this blog, we\u2019ll 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.<\/p>\n\n\n\n<p>Given an array&nbsp;of&nbsp;<code>intervals<\/code>&nbsp;where&nbsp;<code>intervals[i] = [start<sub>i<\/sub>, end<sub>i<\/sub>]<\/code>, merge all overlapping intervals, and return&nbsp;<em>an array of the non-overlapping intervals that cover all the intervals in the input<\/em>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/merge-intervals\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> intervals = [[1,3],[2,6],[8,10],[15,18]]<br><strong>Output:<\/strong> [[1,6],[8,10],[15,18]]<br><strong>Explanation:<\/strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> intervals = [[1,4],[4,5]]<br><strong>Output:<\/strong> [[1,5]]<br><strong>Explanation:<\/strong> Intervals [1,4] and [4,5] are considered overlapping.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= intervals.length &lt;= 10<sup>4<\/sup><\/code><\/li>\n\n\n\n<li><code>intervals[i].length == 2<\/code><\/li>\n\n\n\n<li><code>0 &lt;= start<sub>i<\/sub> &lt;= end<sub>i<\/sub> &lt;= 10<sup>4<\/sup><\/code><\/li>\n<\/ul>\n\n\n<div class=\"wp-block-ub-table-of-contents-block ub_table-of-contents\" id=\"ub_table-of-contents-8670ecbb-976f-4b45-9010-8553ae68f818\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"false\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"true\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column \">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#0-brute-force-solution\" style=\"\">Brute Force Solution<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#4-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#5-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#7-optimal-solution\" style=\"\">Optimal Solution<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#8-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#11-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#12-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/merge-intervals\/#14-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution\">Brute Force Solution<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Let\u2019s solve the problem step by step in the simplest way:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Sort the Intervals:<\/strong><br>Sorting helps us line up all intervals so that overlapping intervals are next to each other.<\/li>\n\n\n\n<li><strong>Check Each Interval:<\/strong><br>For every interval, try to merge it with all future intervals that overlap with it.<\/li>\n\n\n\n<li><strong>Skip Already Merged Intervals:<\/strong><br>If an interval is already covered by a previous merge, skip it.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>We check every possible overlap and merge accordingly. This ensures all intervals are merged correctly, but it\u2019s not the most efficient.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List\n\nclass Solution:\n    def merge(self, intervals: List[List[int]]) -&gt; List[List[int]]:\n        n = len(intervals)\n        intervals.sort()                         # sort intervals by start time\n        ans = []\n        for i in range(n):\n            start, end = intervals[i][0], intervals[i][1]   # current interval\n\n            # skip if current interval is already merged\n            if len(ans) != 0 and end &lt;= ans[-1][1]:\n                continue\n\n            # try to merge with future overlapping intervals\n            for j in range(i + 1, n):\n                if intervals[j][0] &lt;= end:                # overlap found\n                    end = max(end, intervals[j][1])       # extend end to the farthest overlap\n                else:\n                    break                                 # stop if no overlap\n            ans.append([start, end])                      # add merged interval to answer\n        return ans\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">merge<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">intervals<\/span><span style=\"color: #D4D4D4\">: List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]) -&gt; List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(intervals)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        intervals.sort()                         <\/span><span style=\"color: #6A9955\"># sort intervals by start time<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ans = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            start, end = intervals[i][<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">], intervals[i][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]   <\/span><span style=\"color: #6A9955\"># current interval<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># skip if current interval is already merged<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(ans) != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> end &lt;= ans[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># try to merge with future overlapping intervals<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> intervals[j][<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">] &lt;= end:                <\/span><span style=\"color: #6A9955\"># overlap found<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    end = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(end, intervals[j][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">])       <\/span><span style=\"color: #6A9955\"># extend end to the farthest overlap<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">break<\/span><span style=\"color: #D4D4D4\">                                 <\/span><span style=\"color: #6A9955\"># stop if no overlap<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            ans.append([start, end])                      <\/span><span style=\"color: #6A9955\"># add merged interval to answer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> ans<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, we sort the intervals to make overlapping intervals adjacent.<\/li>\n\n\n\n<li>For each interval, we check if it\u2019s already merged; if so, we skip it.<\/li>\n\n\n\n<li>Then, we look ahead to merge all intervals that overlap with the current one.<\/li>\n\n\n\n<li>We add the merged interval to our answer list.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>intervals = [[1],,,]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>After sorting:\u00a0<code>[[1],,,]<\/code><\/li>\n\n\n\n<li>Start with\u00a0<a href=\"https:\/\/leetcode.com\/problems\/merge-intervals\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>.\u00a0overlaps, so merge to\u00a0<a href=\"https:\/\/leetcode.com\/problems\/merge-intervals\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>.<\/li>\n\n\n\n<li>does not overlap, so add .<\/li>\n\n\n\n<li>does not overlap, so add .<\/li>\n\n\n\n<li>Final output:\u00a0<code>[[1],,]<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(N^2)<br>For each interval, we may check all future intervals.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(N)<br>For the answer list.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The brute force approach is easy to understand but slow for large lists. It&#8217;s good for learning the basics of the problem.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-optimal-solution\">Optimal Solution<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>We can solve this problem much faster by merging intervals as we go:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Sort the Intervals:<\/strong><br>Sorting puts overlapping intervals next to each other.<\/li>\n\n\n\n<li><strong>Merge on the Go:<\/strong><br>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.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>After sorting, all overlaps are adjacent, so we only need to look at the last merged interval.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List\n\nclass Solution:\n    def merge(self, intervals: List[List[int]]) -&gt; List[List[int]]:\n        n = len(intervals)\n        intervals.sort()                              # sort intervals by start time\n        ans = []\n        for i in range(n):\n            # if ans is empty or no overlap, add interval\n            if len(ans) == 0 or intervals[i][0] &gt; ans[-1][1]:\n                ans.append(intervals[i])\n            else:\n                # merge with the last interval in ans\n                ans[-1][1] = max(ans[-1][1], intervals[i][1])\n        return ans\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">merge<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">intervals<\/span><span style=\"color: #D4D4D4\">: List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]) -&gt; List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(intervals)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        intervals.sort()                              <\/span><span style=\"color: #6A9955\"># sort intervals by start time<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ans = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># if ans is empty or no overlap, add interval<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(ans) == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> intervals[i][<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">] &gt; ans[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                ans.append(intervals[i])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># merge with the last interval in ans<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                ans[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(ans[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">], intervals[i][<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> ans<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We sort the intervals.<\/li>\n\n\n\n<li>For each interval, if it doesn\u2019t overlap with the last interval in the answer, we add it.<\/li>\n\n\n\n<li>If it does overlap, we merge it with the last interval by updating the end value.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>intervals = [[1],,,]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>After sorting:\u00a0<code>[[1],,,]<\/code><\/li>\n\n\n\n<li><a href=\"https:\/\/leetcode.com\/problems\/merge-intervals\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>: add to answer \u2192\u00a0<code>[[1]]<\/code><\/li>\n\n\n\n<li>: overlaps with\u00a0<a href=\"https:\/\/leetcode.com\/problems\/merge-intervals\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>, merge to\u00a0<a href=\"https:\/\/leetcode.com\/problems\/merge-intervals\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>\u00a0\u2192\u00a0<code>[[1]]<\/code><\/li>\n\n\n\n<li>: no overlap, add \u2192\u00a0<code>[[1],]<\/code><\/li>\n\n\n\n<li>: no overlap, add \u2192\u00a0<code>[[1],,]<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(N log N)<br>Sorting dominates; merging is O(N).<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(N)<br>For the answer list.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The optimal solution is efficient and elegant. It\u2019s the best approach for interviews and large datasets.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"14-final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<p>The &#8220;Merge Intervals&#8221; 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.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you want to master array problems, &#8220;Merge Intervals&#8221; is a must-know question! In this blog, we\u2019ll 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&nbsp;of&nbsp;intervals&nbsp;where&nbsp;intervals[i] = [starti, endi], merge all overlapping intervals, and return&nbsp;an array<\/p>\n","protected":false},"author":1,"featured_media":523,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[7,18],"class_list":{"0":"post-522","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-array","10":"tag-hard"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/merge-intervals-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/522","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=522"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/522\/revisions"}],"predecessor-version":[{"id":524,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/522\/revisions\/524"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/523"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=522"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=522"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=522"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}