{"id":"merge-intervals","title":"Merge Intervals","difficulty":"medium","patterns":["sorting-basics"],"primaryConcept":"sorting-intervals","concepts":["sorting-intervals"],"problemForm":"core","companies":[],"category":"searching-sorting","compareMode":"exact","description":"Given a list of intervals where each interval is `[start, end]`, merge all overlapping intervals and return the merged intervals sorted by start.\n\nRequirements:\n- Intervals overlap when the next start is less than or equal to the current merged end.\n- Touching intervals such as `[1,4]` and `[4,5]` should merge into `[1,5]`.\n- Return a new merged coverage list, not a count.","examples":[{"input":"intervals = [[1,3],[2,6],[8,10],[15,18]]","output":"[[1,6],[8,10],[15,18]]","explanation":"[1,3] and [2,6] overlap, so they merge into [1,6]."},{"input":"intervals = [[1,4],[4,5]]","output":"[[1,5]]","explanation":"The second interval starts exactly at the first interval's end, so they overlap."},{"input":"intervals = [[1,5],[2,3],[3,4],[4,5]]","output":"[[1,5]]","explanation":"Every later interval is already covered by the first merged interval."}],"constraints":[{"id":"0-len-intervals-10-4","text":"0 <= len(intervals) <= 10^4","check":{"kind":"sizeRange","target":"intervals","measure":"arrayLength","min":0,"max":10000}},{"id":"intervals-i-length-2","text":"len(intervals[i]) == 2","check":{"kind":"shape","target":"intervals","shape":"tupleArray","tupleLength":2}},{"id":"0-start-end-10-9","text":"0 <= start <= end <= 10^9","check":[{"kind":"valueRange","target":"intervals","selector":"tupleItemsAtIndex","index":0,"min":0},{"kind":"compare","target":"intervals","left":{"field":0},"op":"<=","right":{"field":1}},{"kind":"valueRange","target":"intervals","selector":"tupleItemsAtIndex","index":1,"max":1000000000}]}],"starterCode":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"merge","testCases":[{"id":"1","input":{"intervals":[[1,3],[2,6],[8,10],[15,18]]},"expected":[[1,6],[8,10],[15,18]],"description":"Standard overlapping pair."},{"id":"2","input":{"intervals":[[1,4],[4,5]]},"expected":[[1,5]],"description":"Touching endpoints merge."},{"id":"3","input":{"intervals":[[1,5],[2,3],[3,4],[4,5]]},"expected":[[1,5]],"description":"Imported fully covered seed case."},{"id":"4","input":{"intervals":[]},"expected":[],"description":"Empty input."},{"id":"5","input":{"intervals":[[5,7],[1,2],[3,4]]},"expected":[[1,2],[3,4],[5,7]],"description":"Disjoint intervals are sorted by start."},{"id":"h1","input":{"intervals":[[1,2],[2,3],[3,4]]},"expected":[[1,4]],"description":"Touching intervals collapse into one range."},{"id":"h2","input":{"intervals":[[1,10],[2,3],[4,8]]},"expected":[[1,10]],"description":"Nested intervals stay covered by the outer span."},{"id":"h3","input":{"intervals":[[5,6],[1,4]]},"expected":[[1,4],[5,6]],"description":"Unsorted disjoint intervals are returned in sorted order."},{"id":"h4","input":{"intervals":[[1,4],[5,7],[8,10]]},"expected":[[1,4],[5,7],[8,10]],"description":"Already-disjoint intervals stay separate."},{"id":"h5","input":{"intervals":[[0,2],[1,5],[7,8],[8,12]]},"expected":[[0,5],[7,12]],"description":"An overlap starting at zero and touching endpoints both merge correctly."},{"id":"unsorted-chain-and-touching-tail","input":{"intervals":[[5,7],[1,3],[2,6],[8,10],[10,12]]},"expected":[[1,7],[8,12]],"description":"An unsorted overlap chain and a touching tail both merge correctly."},{"id":"single-negative-interval","input":{"intervals":[[0,4]]},"expected":[[0,4]],"description":"A single interval starting at zero is returned unchanged."}],"hints":[{"level":1,"content":"After intervals are sorted by start, each new interval only needs to be compared with the last merged interval.","revealPattern":false},{"level":2,"content":"Sort by the first coordinate, seed the result with the first interval, then scan the rest.","revealPattern":true},{"level":3,"content":"If the current start is <= the last merged end, update the last end to max(last end, current end); otherwise append a new interval.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"pairwise","name":"Repeated pairwise merging","summary":"Repeatedly compare every interval against every other interval until no overlaps remain.","decisionReason":"Every merge can create a new interval that overlaps something already checked, so the scan has to restart until nothing changes. That re-checking is the n², and chained overlaps are easy to miss.","complexity":{"time":"O(n^2)","space":"O(n)"},"tradeoffs":["Runs in O(n^2) time and uses O(n) space."],"isOptimal":false},{"id":"sort-and-scan","name":"Sort then scan merged coverage","summary":"Sort intervals by start, then keep a merged result as you scan left to right.","decisionReason":"Once intervals are sorted by start, any overlap must involve the interval currently being grown: the next start either lands inside the merged span or opens a new one. One pass after the sort settles every chain.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"sort-starts","title":"Sort intervals by start","description":"Order intervals by their first coordinate before scanning.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"orders_sequence_by_first_projection_key","scope":"sort","readMode":"sequence-ordering-value-query-v1"}]},"commonMistakes":["Sorting by end instead of start","Skipping sorting and assuming input order"],"hint":"Use the interval start as the sort key.","semanticSpec":{"intent":"Order the interval sequence by each interval's start coordinate.","doneWhen":"This step is done when the input intervals are sorted by their first element before the merge scan.","shouldFailWhen":"This step should fail if the code sorts by the wrong coordinate or does not order the input.","roles":["interval sequence","start coordinate","ordered scan"],"mustProve":["The sequence is ordered before scanning.","The ordering key uses the first coordinate of each interval."],"mustNotAccept":["Sorting by interval end.","Relying on original input order.","Sorting unrelated data."],"equivalentVariants":["Use `intervals.sort(key=lambda interval: interval[0])`.","Use `sorted(intervals, key=lambda interval: interval[0])` with the sorted result scanned afterward."],"proofSnippets":[{"id":"py-merge-intervals-sort","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        intervals.sort(key=lambda interval: interval[0])\n        return intervals"}]}},{"id":"handle-empty","title":"Return an empty merge for empty input","description":"Before reading the first interval, return an empty list when there are no intervals.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"short_circuits_empty_input_with_empty_collection_return","scope":"handle-empty","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Reading intervals[0] before handling empty input","Returning a scalar or None for empty input"],"hint":"Guard the empty case before seeding from the first interval.","semanticSpec":{"intent":"Handle the empty interval list before seeding the merged result.","doneWhen":"This step is done when empty input returns an empty list before any first-interval access is required.","shouldFailWhen":"This step should fail if empty input returns a non-list value or is not guarded.","roles":["input intervals","empty result","first interval access"],"mustProve":["The input interval list is checked for emptiness.","The empty case returns an empty collection."],"mustNotAccept":["Returning 0, None, or another scalar for empty input.","Only relying on intervals[0] without an empty guard."],"equivalentVariants":["Use `if not intervals: return []`.","Use an equivalent zero-length guard that returns an empty list."],"proofSnippets":[{"id":"py-merge-intervals-empty","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        intervals.sort(key=lambda interval: interval[0])\n        if not intervals:\n            return []\n        return intervals"}]}},{"id":"seed-merged","title":"Seed the merged result","description":"Start the merged list with the first sorted interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Starting with an empty result and then forgetting the first interval","Accessing intervals[0] without considering empty input"],"hint":"After the empty case, the first interval is the initial merged coverage.","semanticSpec":{"intent":"Initialize the result sequence from the first sorted interval.","doneWhen":"This step is done when a result list is initialized with the first interval before scanning the remaining intervals.","shouldFailWhen":"This step should fail if no result sequence is initialized before append/update operations.","roles":["result sequence","first interval","sorted input"],"mustProve":["A result sequence is initialized.","The initial result is seeded from the input intervals."],"mustNotAccept":["Only declaring a scalar variable.","Appending without any initialized result sequence."],"equivalentVariants":["Use `merged = [intervals[0]]`.","Use an equivalent initialized result sequence seeded by the first sorted interval."],"proofSnippets":[{"id":"py-merge-intervals-seed","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        if not intervals:\n            return []\n        intervals.sort(key=lambda interval: interval[0])\n        merged = [intervals[0]]\n        return merged"}]}},{"id":"scan-rest","title":"Scan the remaining intervals","description":"Walk through the sorted intervals after the seeded first interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-intervals","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Starting from the first interval again and duplicating it","Using nested pairwise comparisons"],"hint":"After seeding, scan `intervals[1:]`.","semanticSpec":{"intent":"Scan the sorted interval sequence to update merged coverage.","doneWhen":"This step is done when the implementation loops over the interval input and tracks each current interval.","shouldFailWhen":"This step should fail if the code does not scan the interval sequence.","roles":["sorted intervals","current interval","merge scan"],"mustProve":["The code scans the interval sequence.","Each current interval is available for branch decisions."],"mustNotAccept":["A constant result without scanning.","A nested all-pairs loop as the main approach."],"equivalentVariants":["Use `for interval in intervals[1:]`.","Use an equivalent single pass over the sorted intervals."],"proofSnippets":[{"id":"py-merge-intervals-scan","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        if not intervals:\n            return []\n        intervals.sort(key=lambda interval: interval[0])\n        merged = [intervals[0]]\n        for interval in intervals[1:]:\n            left, right = interval\n        return merged"}]}},{"id":"check-overlap","title":"Compare with the last merged interval","description":"Use the current start and previous merged end to decide overlap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"branches_on_interval_overlap","scope":"check-overlap","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Comparing against the first original interval instead of the last merged interval","Using < instead of <= and failing to merge touching endpoints"],"hint":"Compare the current start to `merged[-1][1]`.","semanticSpec":{"intent":"Branch on whether the current interval overlaps the previous merged interval.","doneWhen":"This step is done when the scan compares current start against the last merged end.","shouldFailWhen":"This step should fail if overlap is checked against the wrong interval or coordinate.","roles":["current interval","previous merged interval","overlap branch"],"mustProve":["The branch reads the current interval start.","The branch reads the previous merged interval end.","The overlap condition controls the merge decision."],"mustNotAccept":["Checking only current interval length.","Comparing against an unrelated interval.","Appending every interval without an overlap branch."],"equivalentVariants":["Use `if left <= previous[1]`.","Use equivalent names for current start and previous merged end."],"proofSnippets":[{"id":"py-merge-intervals-overlap","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        if not intervals:\n            return []\n        intervals.sort(key=lambda interval: interval[0])\n        merged = [intervals[0]]\n        for interval in intervals[1:]:\n            left, right = interval\n            previous = merged[-1]\n            if left <= previous[1]:\n                return merged\n        return merged"}]}},{"id":"extend-overlap","title":"Extend overlapping coverage","description":"When intervals overlap, update the last merged end to the larger end.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"extends_previous_interval_end_on_overlap","scope":"merge-overlap","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Replacing the end with the current end and shrinking contained intervals","Appending overlapping intervals instead of extending the previous interval"],"hint":"Use max(previous end, current end).","semanticSpec":{"intent":"Extend the previous merged interval when the current interval overlaps it.","doneWhen":"This step is done when the overlap branch updates the previous merged end with the max of both ends.","shouldFailWhen":"This step should fail if an overlap can shrink the merged end or leave it unchanged.","roles":["previous merged interval","current interval","end extension"],"mustProve":["The overlap branch updates the previous merged interval.","The update considers the current interval end.","The update preserves the larger end."],"mustNotAccept":["Setting the previous end directly to the current end without max behavior.","Appending the current interval on overlap.","Updating the interval start instead of the end."],"equivalentVariants":["Use `previous[1] = max(previous[1], right)`.","Use equivalent mutation of the last merged interval's end."],"proofSnippets":[{"id":"py-merge-intervals-extend","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        if not intervals:\n            return []\n        intervals.sort(key=lambda interval: interval[0])\n        merged = [intervals[0]]\n        for interval in intervals[1:]:\n            left, right = interval\n            previous = merged[-1]\n            if left <= previous[1]:\n                previous[1] = max(previous[1], right)\n        return merged"}]}},{"id":"append-disjoint","title":"Append disjoint intervals","description":"When there is no overlap, start a new merged interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"appends_scan_state_to_result","scope":"append-to-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Dropping disjoint intervals","Overwriting the previous merged interval when there is no overlap"],"hint":"The else branch should append the current interval to merged.","semanticSpec":{"intent":"Append the current interval when it starts after the previous merged end.","doneWhen":"This step is done when the scan can append the current interval to the result sequence.","shouldFailWhen":"This step should fail if disjoint intervals are not added to the output.","roles":["current interval","merged result","append branch"],"mustProve":["The result sequence receives scan items.","The appended item comes from the current interval scan."],"mustNotAccept":["Only updating the previous interval.","Returning the sorted input without building a merged result."],"equivalentVariants":["Use `merged.append(interval)`.","Use an equivalent result append for disjoint current intervals."],"proofSnippets":[{"id":"py-merge-intervals-append","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        if not intervals:\n            return []\n        intervals.sort(key=lambda interval: interval[0])\n        merged = [intervals[0]]\n        for interval in intervals[1:]:\n            left, right = interval\n            previous = merged[-1]\n            if left <= previous[1]:\n                previous[1] = max(previous[1], right)\n            else:\n                merged.append(interval)\n        return 0"}]}},{"id":"return-merged","title":"Return merged coverage","description":"Return the merged interval list after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning the original sorted input","Returning only the last interval"],"hint":"Return the result list that was seeded, extended, and appended to.","semanticSpec":{"intent":"Return the merged interval result sequence.","doneWhen":"This step is done when the function returns the result sequence after the merge scan.","shouldFailWhen":"This step should fail if the returned value is not the built merged result.","roles":["merged result","terminal return"],"mustProve":["The result sequence is initialized.","The result sequence is updated during the scan.","The terminal return is that result sequence."],"mustNotAccept":["Returning `intervals` directly.","Returning a scalar count.","Returning before scanning intervals."],"equivalentVariants":["Return `merged` after the loop.","Return an equivalent result sequence after all merge updates."],"proofSnippets":[{"id":"py-merge-intervals-return","language":"python","code":"class Solution:\n    def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n        if not intervals:\n            return []\n        intervals.sort(key=lambda interval: interval[0])\n        merged = [intervals[0]]\n        for interval in intervals[1:]:\n            left, right = interval\n            previous = merged[-1]\n            if left <= previous[1]:\n                previous[1] = max(previous[1], right)\n            else:\n                merged.append(interval)\n        return merged"}]}}],"version":2,"progressRevision":"merge-intervals-2026-07-19-sort-before-last-merged-invariant","slides":[{"id":"read-the-problem","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Collapse overlapping ranges into one","workspacePanel":"problem","body":["You get a list of intervals, each written [start, end]. Some of them overlap, and the job is to fuse every overlapping run into a single covering interval, then return that smaller list.","Two intervals count as overlapping the moment one starts at or before the other ends: an interval that begins exactly where another stops still fuses with it into one span."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Keep merging any pair that overlaps","summary":"Fusing any overlapping pair and rescanning gets the coverage right, but every merge can trigger another full sweep. Watch how many times the same pairs get compared.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"changed = True\nwhile changed:\n    changed = False\n    for a in range(len(intervals)):\n        for b in range(a + 1, len(intervals)):\n            if intervals[a][0] <= intervals[b][1] and intervals[b][0] <= intervals[a][1]:\n                intervals[a] = [min(intervals[a][0], intervals[b][0]), max(intervals[a][1], intervals[b][1])]\n                intervals.pop(b)\n                changed = True\n                break","steps":[{"id":"scan-pairs","title":"Compare a against every later interval","codeLine":5,"summary":"intervals = [[1,3],[2,6],[8,10]]. a is on [1,3]; b sweeps [2,6] then [8,10], one pair at a time.","state":{"grid":[[1,3],[2,6],[8,10]],"labels":{"grid":"intervals"},"r":0}},{"id":"merge-pair","title":"A pair overlaps, so fuse and delete one","codeLine":7,"summary":"[1,3] and [2,6] overlap, so [1,3] becomes [1,6] and the [2,6] entry is removed. The list shrank by one.","state":{"grid":[[1,6],[8,10]],"labels":{"grid":"intervals"},"r":0,"filled":[[0,0],[0,1]]}},{"id":"restart-pass","title":"One merge forces another full pass","codeLine":2,"summary":"changed was set, so the whole double loop runs again from the top to confirm nothing else overlaps.","state":{"grid":[[1,6],[8,10]],"labels":{"grid":"intervals"},"r":0}},{"id":"settle","title":"A clean pass ends it","codeLine":9,"summary":"This pass finds no overlap, so changed stays False and the loop stops. The result is [[1,6],[8,10]].","state":{"grid":[[1,6],[8,10]],"labels":{"grid":"intervals"},"r":1}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let changed = true;\nwhile (changed) {\n    changed = false;\n    for (let a = 0; a < intervals.length; a++) {\n        for (let b = (a + 1); b < intervals.length; b++) {\n            if (intervals[a][0] <= intervals[b][1] && intervals[b][0] <= intervals[a][1]) {\n                intervals[a] = [Math.min(intervals[a][0], intervals[b][0]), Math.max(intervals[a][1], intervals[b][1])];\n                intervals.splice(b, 1)[0];\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10},"statementBundles":{"10":{"startLine":10,"endLine":14}},"alternateStyles":{"close-to-source":{"code":"let changed = true;\nwhile (changed) {\n    changed = false;\n    for (let a = 0; a < intervals.length; a++) {\n        for (let b = (a + 1); b < intervals.length; b++) {\n            if (intervals[a][0] <= intervals[b][1] && intervals[b][0] <= intervals[a][1]) {\n                intervals[a] = [Math.min(intervals[a][0], intervals[b][0]), Math.max(intervals[a][1], intervals[b][1])];\n                const poppedValue = intervals.splice(b, 1)[0];\n                if (poppedValue === undefined) throw new Error(\"IndexError\");\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":15}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let changed = true;\nwhile (changed) {\n    changed = false;\n    for (let a = 0; a < intervals.length; a++) {\n        for (let b = (a + 1); b < intervals.length; b++) {\n            if (intervals[a][0] <= intervals[b][1] && intervals[b][0] <= intervals[a][1]) {\n                intervals[a] = [Math.min(intervals[a][0], intervals[b][0]), Math.max(intervals[a][1], intervals[b][1])];\n                intervals.splice(b, 1)[0];\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10},"statementBundles":{"10":{"startLine":10,"endLine":14}},"alternateStyles":{"close-to-source":{"code":"let changed = true;\nwhile (changed) {\n    changed = false;\n    for (let a = 0; a < intervals.length; a++) {\n        for (let b = (a + 1); b < intervals.length; b++) {\n            if (intervals[a][0] <= intervals[b][1] && intervals[b][0] <= intervals[a][1]) {\n                intervals[a] = [Math.min(intervals[a][0], intervals[b][0]), Math.max(intervals[a][1], intervals[b][1])];\n                const poppedValue = intervals.splice(b, 1)[0];\n                if (poppedValue === undefined) throw new Error(\"IndexError\");\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":15}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"boolean changed = true;\nwhile (changed) {\n    changed = false;\n    for (int a = 0; a < intervals.size(); a++) {\n        for (int b = (a + 1); b < intervals.size(); b++) {\n            if ((intervals.get(a).get(0) <= intervals.get(b).get(1) && intervals.get(b).get(0) <= intervals.get(a).get(1))) {\n                intervals.set(a, new ArrayList<>(List.of(Math.min(intervals.get(a).get(0), intervals.get(b).get(0)), Math.max(intervals.get(a).get(1), intervals.get(b).get(1)))));\n                intervals.remove(b);\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10},"statementBundles":{"10":{"startLine":10,"endLine":14}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"bool changed = true;\nwhile (changed) {\n    changed = false;\n    for (int a = 0; a < intervals.Count; a++) {\n        for (int b = a + 1; b < intervals.Count; b++) {\n            if (intervals[a][0] <= intervals[b][1] && intervals[b][0] <= intervals[a][1]) {\n                intervals[a] = new List<int> { Math.Min(intervals[a][0], intervals[b][0]), Math.Max(intervals[a][1], intervals[b][1]) };\n                intervals.RemoveAt(b);\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10},"statementBundles":{"10":{"startLine":10,"endLine":14}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"bool changed = true;\nwhile (changed) {\n    changed = false;\n    for (int a = 0; a < intervals.size(); a++) {\n        for (int b = (a + 1); b < intervals.size(); b++) {\n            if ((intervals[a][0] <= intervals[b][1] && intervals[b][0] <= intervals[a][1])) {\n                intervals[a] = vector<int>{min(intervals[a][0], intervals[b][0]), max(intervals[a][1], intervals[b][1])};\n                intervals.erase(intervals.begin() + b);\n                changed = true;\n                break;\n            }\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10},"statementBundles":{"10":{"startLine":10,"endLine":14}}}}},"body":["Compare every interval with every later one. Whenever two overlap, fuse them and drop the spare, then start the whole scan over because the fused interval might now reach the next one."]},{"id":"cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Count the cost","title":"What drives the cost of repeated merging?","summary":"Each merge can force another full pass over every remaining pair.","workspacePanel":"trace","options":[{"id":"passes-times-pairs","label":"Repeated re-searching: one pass already scans many pairs, and a chain can force a fresh pass after almost every merge","rationale":"A single all-pairs sweep is already costly, but the real pain is doing it again and again: each fusion can expose the next overlap, so the double loop restarts. The next strategy has to avoid rediscovering the same neighborhood after every merge.","isCorrect":true},{"id":"deleting","label":"Deleting entries: removing the spare interval from the list is the slow part","rationale":"A single delete is cheap relative to the bigger problem. The cost comes from re-comparing every remaining pair again after each merge, not from the removal itself.","isCorrect":false},{"id":"constant","label":"Almost nothing: most lists settle after one pass","rationale":"A long overlapping chain merges one pair per pass, so it can take a pass for nearly every interval. Nothing guarantees an early finish.","isCorrect":false}],"answer":"Each fusion can expose a new overlap, so the double loop reruns again and again. The cost is passes times pairs: one all-pairs sweep is already expensive, and repeating it after almost every merge is what the next idea has to cut down by searching for overlaps just once."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the move","title":"Which one move makes overlap cheap to check?","workspacePanel":"trace","quiz":{"contract":"pattern-recognition-v1","question":"Which one move makes overlap cheap to check?","signalPrompt":"The repeated cost is comparing each interval against all the others. Which arrangement of the intervals would limit how far each one has to look?","options":[{"id":"sort-by-start","label":"Sort the intervals by their start","signal":"Putting the intervals in start order lines them up so each one only has to look at coverage already built, instead of searching the whole list.","rationale":"One ordering replaces the repeated all-pairs search: in start order the intervals arrive left to right, so a single pass can fuse them. Exactly how far back each interval has to check is the next thing to pin down.","isCorrect":true},{"id":"two-pointers","label":"Walk two pointers inward from both ends","signal":"Two pointers shine on a sorted array when the answer is a pair found by closing in from the outside.","rationale":"Merging is not a search for one pair from the ends; it is a single left-to-right consolidation, so converging pointers do not fit.","isCorrect":false},{"id":"heap","label":"Push every interval into a heap","signal":"A heap can hand back intervals in start order one at a time.","rationale":"A heap would order them too, but sorting once does the same job and then gives the scan its invariant directly, with less machinery.","isCorrect":false},{"id":"binary-search","label":"Binary search for each interval's neighbor","signal":"Binary search jumps straight to a position in a sorted list.","rationale":"There is no fixed target value to locate; the work is fusing a sorted run as you pass through it, not finding one index.","isCorrect":false}],"missFeedback":"The expensive part is looking everywhere for an overlap. Put the intervals in start order and that search shrinks to a single left-to-right pass."}},{"id":"approach-selection","chapter":"The idea","kind":"info","eyebrow":"Name the approach","title":"Sort once, then build merged coverage from left to right","workspacePanel":"trace","body":["Sorting by start fixes the order in which coverage can appear. Instead of restarting an all-pairs search after every fusion, scan the sorted intervals once and fold each one into the coverage already built.","The sort costs O(n log n) and the scan costs O(n). To make that scan precise, we still have to decide how much of the earlier merged coverage the current interval could possibly overlap."]},{"id":"overlap-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"After sorting, which interval can the current one overlap?","summary":"intervals are sorted by start; merged holds the coverage built so far.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"overlap-invariant-state","state":{"grid":[[1,6],[8,10],[15,18]],"labels":{"grid":"intervals"},"r":1,"c":0,"filled":[[0,0],[0,1]]}}]},"options":[{"id":"only-last-merged","label":"Only the last interval already in merged","rationale":"Every earlier interval starts no later than the current one, so the current start can only fall inside the most recent coverage. If it clears that interval's end, it clears every earlier one too.","isCorrect":true},{"id":"any-earlier","label":"Any of the earlier merged intervals","rationale":"Sorted order rules the older ones out. They all end no later than the last merged interval, so if the current start is past the latest end it is past all of them.","isCorrect":false},{"id":"the-next-one","label":"The interval that comes after it","rationale":"The scan moves left to right, so a later interval has not been reached yet. Overlap is always decided against coverage already built, never ahead.","isCorrect":false}],"answer":"Just the last merged interval. Because starts are sorted, the current interval's start sits at or after every earlier start, so the only end it could reach back into is the most recent one."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Seed merged with the first interval","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"grid":[[1,3],[2,6],[4,5],[8,10]],"labels":{"grid":"intervals"},"r":0,"filled":[[0,0],[0,1]]}}]},"body":["Sorted, the input is [[1,3],[2,6],[4,5],[8,10]]. The first interval has nothing before it, so it becomes the starting coverage: merged is [[1,3]].","From there each interval asks one question against the last merged interval: does my start reach its end? If yes, stretch that interval's end; if no, I start a new piece of coverage.","The next three beats walk that scan one interval at a time."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the scan","title":"Trace the sort-and-scan merge","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"extend-overlap","state":{"grid":[[1,3],[2,6],[4,5],[8,10]],"labels":{"grid":"intervals"},"r":1,"c":0,"filled":[[0,0],[0,1]]}},{"id":"why-max","state":{"grid":[[1,6],[4,5],[8,10]],"labels":{"grid":"intervals"},"r":1,"c":0,"filled":[[0,0],[0,1]]}},{"id":"append-disjoint","state":{"grid":[[1,6],[8,10]],"labels":{"grid":"intervals"},"r":1,"c":0,"filled":[[0,0],[0,1],[1,0],[1,1]]}}]},"beats":[{"id":"extend-overlap","title":"[2,6] arrives. Does it overlap the last merged interval?","summary":"merged ends at [1,3]; the current interval is [2,6].","prompt":"The current start is 2 and the last merged end is 3.","options":[{"id":"overlaps-extend","label":"Yes: 2 is at or before 3, so extend the merged end out to 6","rationale":"The current start lands inside the last coverage, so the two pieces are one stretch. The merged interval grows to [1,6].","isCorrect":true},{"id":"append-new","label":"No: append [2,6] as a separate interval","rationale":"A separate piece would only be right if 2 were past 3. Since 2 is not, the intervals touch and must fuse.","isCorrect":false},{"id":"replace","label":"Yes, overlaps: replace [1,3] with [2,6]","rationale":"Replacing would throw away the start 1. The fused interval has to keep the earliest start, so it spans [1,6].","isCorrect":false}],"answer":"2 is at or before 3, so they overlap. The last merged interval stretches to [1,6], keeping the earlier start."},{"id":"why-max","title":"Why take max(previous end, current end) instead of just the current end?","summary":"merged is [[1,6]]; the next sorted interval is [4,5].","prompt":"[4,5] starts at 4, which is at or before the merged end 6, so it overlaps.","options":[{"id":"max-keeps-cover","label":"A contained interval ends earlier, so taking its end would shrink the coverage","rationale":"[4,5] sits entirely inside [1,6]. Setting the end to 5 would drop the stretch from 5 to 6 that the merged interval already covers, so the larger end has to win.","isCorrect":true},{"id":"max-pointless","label":"It never matters; sorted starts mean the current end is always larger","rationale":"Sorting orders the starts. A later interval can still finish earlier, exactly as [4,5] does inside [1,6].","isCorrect":false},{"id":"max-for-touch","label":"It only matters for intervals that merely touch at an endpoint","rationale":"Touching is a separate concern about the overlap test. The max guards against a fully contained interval shrinking coverage, which can happen whether or not endpoints touch.","isCorrect":false}],"answer":"Sorted starts say nothing about ends, so a later interval can be contained. max keeps the further end and the coverage never shrinks."},{"id":"append-disjoint","title":"[8,10] arrives. What happens to merged?","summary":"The built coverage is [1,6], and the scan is reading [8,10].","prompt":"Compare start 8 with coverage end 6.","options":[{"id":"append","label":"Append [8,10] as a new merged interval","rationale":"8 is past 6, so there is no overlap to fuse. It opens a fresh piece of coverage and merged becomes [[1,6],[8,10]].","isCorrect":true},{"id":"extend-wrong","label":"Extend the last merged end to 10","rationale":"Extending would invent coverage over 6 to 8 that no interval claims. With no overlap, the gap must stay a gap.","isCorrect":false},{"id":"skip","label":"Skip it, since it does not touch the previous interval","rationale":"Skipping would drop real coverage. A disjoint interval is still part of the answer; it just starts its own piece.","isCorrect":false}],"answer":"8 is past 6, so [8,10] starts a new piece. merged ends as [[1,6],[8,10]], its standing invariant: non-overlapping coverage of everything scanned so far."}]},{"id":"replace-end-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"The bug that passes the obvious tests, then loses coverage","summary":"previous[1] = right is the line most people write first, and it sails through [[1,3],[2,6]] -> [1,6]. The failure only surfaces on a contained interval, so it slips past quick checks and corrupts the answer in production. Watch exactly where the coverage disappears.","workspacePanel":"trace","pitfall":"The code below sets previous[1] = right on every overlap, instead of max(previous[1], right).","whyItMatters":"The visible symptom: a returned interval is shorter than an input it supposedly absorbed. Here [1,5] swallows [2,3] but comes back as [1,3]. Whenever a merged span can shrink, the overwrite is the culprit and max(previous[1], right) is the fix.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"merged = [intervals[0]]\nfor interval in intervals[1:]:\n    left, right = interval\n    previous = merged[-1]\n    if left <= previous[1]:\n        previous[1] = right\n    else:\n        merged.append(interval)","steps":[{"id":"seed","title":"merged starts as [1,5]","codeLine":1,"summary":"intervals = [[1,5],[2,3],[6,8]], already sorted. The first interval seeds the coverage.","state":{"grid":[[1,5],[2,3],[6,8]],"labels":{"grid":"intervals"},"r":0,"filled":[[0,0],[0,1]]}},{"id":"contained-overlap","title":"[2,3] overlaps and is fully inside [1,5]","codeLine":5,"summary":"left is 2, previous end is 5, so 2 <= 5 is true. The intervals overlap, and [2,3] lies entirely within [1,5].","state":{"grid":[[1,5],[2,3],[6,8]],"labels":{"grid":"intervals"},"r":1,"filled":[[0,0],[0,1]]}},{"id":"end-shrinks","title":"The end is overwritten with 3","codeLine":6,"summary":"previous[1] = right sets the merged end to 3. The coverage just lost the stretch from 3 to 5 that [1,5] already owned.","state":{"grid":[[1,3],[6,8]],"labels":{"grid":"intervals"},"r":0,"filled":[[0,0],[0,1]]}},{"id":"wrong-result","title":"Coverage lost, and wrong","codeLine":8,"summary":"[6,8] starts past 3, so it appends. The result is [[1,3],[6,8]], but the true coverage was [[1,5],[6,8]].","state":{"grid":[[1,3],[6,8]],"labels":{"grid":"intervals"},"r":1,"filled":[[0,0],[0,1],[1,0],[1,1]]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const merged = [intervals[0]];\nfor (const interval of intervals.slice(1)) {\n    const [left, right] = interval;\n    const previous = merged[(merged.length - 1)];\n    if (left <= previous[1]) {\n        previous[1] = right;\n    } else {\n        merged.push(interval);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8},"statementBundles":{"8":{"startLine":8,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const merged = [intervals[0]];\nfor (const interval of intervals.slice(1)) {\n    const [left, right] = interval;\n    const previous = merged[(merged.length - 1)];\n    if (left <= previous[1]) {\n        previous[1] = right;\n    } else {\n        merged.push(interval);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8},"statementBundles":{"8":{"startLine":8,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> merged = new ArrayList<>(List.of(intervals.get(0)));\nfor (List<Integer> interval : new ArrayList<List<Integer>>(intervals.subList(1, intervals.size()))) {\n    int left = interval.get(0);\n    int right = interval.get(1);\n    List<Integer> previous = merged.get((merged.size() - 1));\n    if (left <= previous.get(1)) {\n        previous.set(1, right);\n    } else {\n        merged.add(interval);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> merged = new() { intervals[0] };\nforeach (var interval in intervals.GetRange(1, intervals.Count - 1)) {\n    int left = interval[0];\n    int right = interval[1];\n    List<int> previous = merged[merged.Count - 1];\n    if (left <= previous[1]) {\n        previous[1] = right;\n    } else {\n        merged.Add(interval);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> merged{intervals[0]};\nfor (vector<int> interval : vector<vector<int>>(intervals.begin() + 1, intervals.begin() + intervals.size())) {\n    int left = interval[0];\n    int right = interval[1];\n    vector<int>& previous = merged[(merged.size() - 1)];\n    if (left <= previous[1]) {\n        previous[1] = right;\n    } else {\n        merged.push_back(interval);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"Two intervals that touch at a shared endpoint, and a call with no intervals at all.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-case-baseline","state":{"grid":[[1,4],[4,5]],"labels":{"grid":"intervals"},"r":1,"filled":[[0,0],[0,1]]}}]},"body":["An interval whose start equals the previous end, and a call with no intervals at all.","Each one tests where the overlap rule and the seeding step draw their line. The next two probes decide whether either needs special handling."]},{"id":"touching-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Do [1,4] and [4,5] merge?","summary":"The current start is 4 and the last merged end is also 4.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"touching-state","state":{"grid":[[1,4],[4,5]],"labels":{"grid":"intervals"},"r":1,"c":0,"filled":[[0,0],[0,1]]}}]},"options":[{"id":"merge-with-le","label":"Yes, into [1,5], because the test uses start <= end","rationale":"The problem counts a start that equals the previous end as overlap, so 4 <= 4 is true and the intervals fuse to [1,5]. A strict < would split them and fail the rule.","isCorrect":true},{"id":"split-with-lt","label":"No, they stay separate, because 4 is not strictly less than 4","rationale":"Strict less-than is the wrong test here. The closed-interval rule treats touching endpoints as overlapping, so this would wrongly return two intervals.","isCorrect":false},{"id":"needs-branch","label":"Only with a special case that checks for equal endpoints","rationale":"No extra branch is needed. Using <= in the one overlap test already folds the touching case into the normal merge.","isCorrect":false}],"answer":"Yes, into [1,5]. The overlap test is start <= previous end, so equal endpoints count as overlap and the single <= handles touching with no special case."},{"id":"empty-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does the scan do with no intervals?","summary":"intervals = [], so there is no first interval to seed coverage with.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-state","state":{"nums":[],"labels":{"nums":"intervals"}}}]},"options":[{"id":"guard-empty","label":"It needs an early return, because seeding reads the first interval","rationale":"merged starts from intervals[0], and an empty list has no element 0. A short guard that returns the empty list before seeding keeps the scan safe.","isCorrect":true},{"id":"loop-handles","label":"Nothing special: the scan loop just runs zero times","rationale":"The loop would be fine, but the seeding line runs before it and reads intervals[0] on an empty list, which is the failure the guard prevents.","isCorrect":false},{"id":"returns-zero","label":"It returns a count of zero","rationale":"The answer is a merged coverage list. With no intervals the correct result is an empty list.","isCorrect":false}],"answer":"It needs a guard. Seeding merged from intervals[0] reads element 0, which does not exist when the list is empty, so return the empty list first."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"One scan, one comparison against the last merged interval, and the larger end wins.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"grid":[[1,3],[2,6],[8,10],[15,18]],"labels":{"grid":"intervals"},"r":0,"filled":[[0,0],[0,1]]}}]},"body":["Guard the empty list, sort by start, and seed the coverage with the first interval. Then walk the rest: when a start reaches the last merged end, stretch that end to the further of the two; otherwise open a new piece of coverage. Return the merged list."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the scan","title":"Build the sort-and-scan merge","summary":"Now turn the scan into code: sort by start, seed merged with the first interval, then walk the rest, comparing each start to the last merged end and either stretching that end to the larger of the two or appending a new piece, and return the merged list.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Sort by start, then each interval only ever argues with the last merged one.","workspacePanel":"code","body":["Merge Intervals is really a sorting problem in disguise. Ordering by start turns a tangle of pairwise comparisons into a single left-to-right pass.","After sorting, the last merged interval carries everything you need: if the next start reaches its end, stretch it; if not, start a new piece."],"takeaways":[{"title":"Sorting collapses the search","body":"In start order the only interval that can overlap the current one is the last merged interval, so the all-pairs scan becomes one pass: O(n log n) for the sort, O(n) for the merge."},{"title":"The larger end always wins","body":"Sorted starts say nothing about ends, so a later interval can be contained. Taking max(previous end, current end) keeps the coverage from ever shrinking."},{"title":"Touching counts as overlap","body":"The test is start <= previous end, so [1,4] and [4,5] fuse into [1,5]. The single <= folds the touching case in with no special branch."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"intervals","primaryParam":"intervals","sizeMetric":"length"}}
