{"id":"insert-interval","title":"Insert Interval","difficulty":"medium","patterns":["sorting-basics"],"primaryConcept":"sorting-intervals","concepts":["sorting-intervals"],"problemForm":"core","companies":[],"category":"searching-sorting","compareMode":"exact","description":"Given a sorted list of non-overlapping intervals and one new interval, insert the new interval and merge any overlaps.\n\nRequirements:\n- The input intervals are already sorted by start.\n- Intervals overlap when the next start is less than or equal to the current merged end.\n- Return the final non-overlapping intervals sorted by start.","examples":[{"input":"intervals = [[1,3],[6,9]], newInterval = [2,5]","output":"[[1,5],[6,9]]","explanation":"[2,5] overlaps [1,3], so they merge into [1,5]."},{"input":"intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]","output":"[[1,2],[3,10],[12,16]]","explanation":"The new interval connects [3,5], [6,7], and [8,10]."},{"input":"intervals = [], newInterval = [5,7]","output":"[[5,7]]","explanation":"With no existing intervals, the new interval is the entire result."}],"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":"newinterval-length-2","text":"len(newInterval) == 2","check":{"kind":"sizeRange","target":"newInterval","measure":"arrayLength","min":2,"max":2}},{"id":"0-start-end-10-9","text":"0 <= start <= end <= 10^9"},{"id":"intervals-is-sorted-by-start-and-contains-no-overlapping-interva","text":"intervals is sorted by start and contains no overlapping intervals"}],"starterCode":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"insert","testCases":[{"id":"1","input":{"intervals":[[1,3],[6,9]],"newInterval":[2,5]},"expected":[[1,5],[6,9]],"description":"New interval overlaps the first interval."},{"id":"2","input":{"intervals":[[1,2],[3,5],[6,7],[8,10],[12,16]],"newInterval":[4,8]},"expected":[[1,2],[3,10],[12,16]],"description":"New interval bridges several existing intervals."},{"id":"3","input":{"intervals":[],"newInterval":[5,7]},"expected":[[5,7]],"description":"Empty interval list."},{"id":"4","input":{"intervals":[[1,5]],"newInterval":[2,3]},"expected":[[1,5]],"description":"New interval is contained inside an existing interval."},{"id":"5","input":{"intervals":[[1,5]],"newInterval":[6,8]},"expected":[[1,5],[6,8]],"description":"New interval belongs after every existing interval."},{"id":"6","input":{"intervals":[[1,5]],"newInterval":[1,5]},"expected":[[1,5]],"description":"Imported seed case with identical interval."},{"id":"h1","input":{"intervals":[[1,2],[3,5],[6,7],[8,10],[12,16]],"newInterval":[0,0]},"expected":[[0,0],[1,2],[3,5],[6,7],[8,10],[12,16]],"description":"A new interval can land before everything else."},{"id":"h2","input":{"intervals":[[1,2],[3,5],[6,7],[8,10],[12,16]],"newInterval":[17,19]},"expected":[[1,2],[3,5],[6,7],[8,10],[12,16],[17,19]],"description":"A new interval can append after everything else."},{"id":"h3","input":{"intervals":[[1,2],[3,5],[6,7],[8,10],[12,16]],"newInterval":[2,13]},"expected":[[1,16]],"description":"One wide interval can merge the whole middle section."},{"id":"h4","input":{"intervals":[[1,2],[3,5],[7,9]],"newInterval":[2,6]},"expected":[[1,6],[7,9]],"description":"Touching endpoints should still merge."},{"id":"topup-1","input":{"intervals":[[1,3],[6,9]],"newInterval":[3,6]},"expected":[[1,9]],"description":"Top-up case 1: touching both neighboring intervals should bridge them into one interval."},{"id":"topup-2","input":{"intervals":[[0,1],[5,6],[8,9]],"newInterval":[2,3]},"expected":[[0,1],[2,3],[5,6],[8,9]],"description":"Top-up case 2: a non-overlapping interval can be inserted into the middle without merging."}],"hints":[{"level":1,"content":"Because the existing intervals are sorted, copy everything that ends before the new interval starts.","revealPattern":false},{"level":2,"content":"Once an interval overlaps the new interval, merge it into the new interval by shrinking the start and extending the end.","revealPattern":true},{"level":3,"content":"After all overlaps are absorbed, append the merged new interval, then copy the remaining intervals.","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":"resort-all","name":"Append, sort, then merge","summary":"Add the new interval to the list, sort all intervals, then run the standard merge-intervals scan.","decisionReason":"The original intervals are already sorted and non-overlapping, so sorting after appending newInterval repeats order work the input already did. Only the span that overlaps newInterval can change.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space."],"isOptimal":false},{"id":"single-pass","name":"Single pass through sorted intervals","summary":"Copy intervals before the new interval, merge all overlaps into it, then copy intervals after it.","decisionReason":"The sorted input splits into intervals before newInterval, intervals that merge into it, and intervals after it. One scan copies the first group, grows newInterval across overlaps, then copies the rest.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Set up result state","description":"Create an empty output list before scanning intervals.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-empty-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Trying to mutate intervals in place without tracking output order","Seeding the output with newInterval before its position is known"],"hint":"Start with an empty result list.","semanticSpec":{"intent":"Initialize the result sequence that will receive intervals in final order.","doneWhen":"This step is done when a result list exists before append and return operations.","shouldFailWhen":"This step should fail if no result sequence is initialized.","roles":["result sequence"],"mustProve":["An empty result sequence is initialized before scan output is appended."],"mustNotAccept":["Only declaring scalar cursor variables.","Returning the input list directly."],"equivalentVariants":["Use `result = []` before scanning."],"proofSnippets":[{"id":"py-insert-interval-init","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        return result"}]}},{"id":"scan-intervals","title":"Scan the sorted intervals","description":"Walk through the interval list with one cursor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Using nested pairwise merging","Restarting the scan after each merge"],"hint":"Keep one index and advance it as intervals are copied or merged.","semanticSpec":{"intent":"Scan the interval input once in sorted order.","doneWhen":"This step is done when the implementation loops over the interval input with a cursor.","shouldFailWhen":"This step should fail if the code never scans the interval sequence.","roles":["interval sequence","scan cursor"],"mustProve":["The code scans the interval sequence.","The scan exposes the current interval for later decisions."],"mustNotAccept":["Returning a constant interval list.","Only sorting without scanning."],"equivalentVariants":["Use `while i < n` loops with one cursor.","Use an equivalent single pass through intervals."],"proofSnippets":[{"id":"py-insert-interval-scan","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            i += 1\n        return 0"}]}},{"id":"append-disjoint","title":"Copy disjoint intervals","description":"Append intervals that do not overlap the new interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"appends_scan_state_to_result","scope":"append-disjoint-regions","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Dropping intervals that come before the new interval","Forgetting to append intervals that come after the new interval"],"hint":"Intervals ending before the new start can be appended immediately.","semanticSpec":{"intent":"Append scanned interval values into the result sequence.","doneWhen":"This step is done when scan items can be copied into the output result.","shouldFailWhen":"This step should fail if scanned intervals are never appended to the result.","roles":["current interval","result sequence"],"mustProve":["The result sequence receives values from the interval scan."],"mustNotAccept":["Only updating newInterval.","Returning without copying scanned intervals."],"equivalentVariants":["Use `result.append(intervals[i])` for intervals outside the overlap region."],"proofSnippets":[{"id":"py-insert-interval-append","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        return 0"}]}},{"id":"check-overlap","title":"Detect overlapping intervals","description":"Continue merging while the current interval starts at or before the merged new interval ends.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"branches_on_interval_overlap","scope":"check-touching-overlap","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Using < instead of <= and missing touching intervals","Comparing against the wrong endpoint"],"hint":"An interval overlaps when `intervals[i][0] <= newInterval[1]`.","semanticSpec":{"intent":"Branch or continue based on interval overlap against the tracked merged interval.","doneWhen":"This step is done when current interval start is compared against the tracked interval end.","shouldFailWhen":"This step should fail if overlap is not tested against the interval end.","roles":["current interval","tracked interval","overlap branch"],"mustProve":["The scan checks current start against the tracked interval end.","The condition controls the merge region."],"mustNotAccept":["Checking only interval length.","Appending every interval without overlap logic."],"equivalentVariants":["Use `while i < n and intervals[i][0] <= newInterval[1]`.","Use an equivalent overlap condition around a merge branch."],"proofSnippets":[{"id":"py-insert-interval-overlap-check","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            i += 1\n        result.append(newInterval)\n        return 0"}]}},{"id":"merge-overlaps","title":"Expand the merged interval","description":"Absorb each overlapping interval by updating both bounds of the new interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"expands_tracked_interval_bounds_on_overlap","scope":"merge-overlap","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Only updating the end and losing intervals that start earlier","Setting the end directly to the current end and shrinking coverage"],"hint":"Use min for the start and max for the end.","semanticSpec":{"intent":"Merge overlapping intervals into the tracked new interval by expanding both bounds.","doneWhen":"This step is done when overlap handling updates the tracked start from min and tracked end from max.","shouldFailWhen":"This step should fail if overlap handling only updates one bound or can shrink coverage.","roles":["tracked interval","current interval","bound expansion"],"mustProve":["The overlap region updates the tracked start with the current interval.","The overlap region updates the tracked end with the current interval."],"mustNotAccept":["Updating only the end.","Appending overlapping intervals separately.","Replacing bounds without preserving the wider coverage."],"equivalentVariants":["Use `newInterval[0] = min(newInterval[0], intervals[i][0])` and `newInterval[1] = max(newInterval[1], intervals[i][1])`."],"proofSnippets":[{"id":"py-insert-interval-merge","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            newInterval[0] = min(newInterval[0], intervals[i][0])\n            newInterval[1] = max(newInterval[1], intervals[i][1])\n            i += 1\n        result.append(newInterval)\n        return 0"}]}},{"id":"return-result","title":"Return final interval list","description":"Return the result sequence after all before, merged, and after intervals are included.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning newInterval only","Returning intervals without the inserted interval"],"hint":"Return the result list after appending the merged new interval and the suffix intervals.","semanticSpec":{"intent":"Return the built result sequence.","doneWhen":"This step is done when the terminal return is the result list populated during the scan.","shouldFailWhen":"This step should fail if the code returns a scalar, the original input, or only the new interval.","roles":["result sequence","terminal return"],"mustProve":["The result sequence is returned after scan appends."],"mustNotAccept":["Returning `newInterval`.","Returning `intervals` directly.","Returning before overlap processing."],"equivalentVariants":["Return `result` after all scanning is complete."],"proofSnippets":[{"id":"py-insert-interval-return","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            newInterval[0] = min(newInterval[0], intervals[i][0])\n            newInterval[1] = max(newInterval[1], intervals[i][1])\n            i += 1\n        result.append(newInterval)\n        while i < n:\n            result.append(intervals[i])\n            i += 1\n        return result"}]}}],"version":2,"slides":[{"id":"read-the-problem","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Slot one interval into a sorted list","workspacePanel":"problem","body":["You are given a list of intervals already sorted by start with no two overlapping, plus one new interval to add. Wherever the new interval lands, any intervals it touches must fuse with it into a single wider interval, and the result stays sorted with no overlaps.","The reflexive move is to build a brand-new list with the interval slotted into place, then sweep that list to fuse touching neighbors. Watch how much it rebuilds."]},{"id":"naive-insert","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Build a new list, then merge it","summary":"Walk the intervals to splice the new one in at its sorted position, building a fresh combined list, then sweep that list fusing each interval into the previous one when they touch. Watch how many lists it builds.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"combined = []\nplaced = False\nfor k in range(len(intervals)):\n    cur = intervals[k]\n    if not placed and newInterval[0] < cur[0]:\n        combined.append(newInterval)\n        placed = True\n    combined.append(cur)\nif not placed:\n    combined.append(newInterval)\nresult = []\nfor k in range(len(combined)):\n    cur = combined[k]\n    if result and cur[0] <= result[len(result) - 1][1]:\n        last = result[len(result) - 1]\n        last[1] = max(last[1], cur[1])\n    else:\n        result.append(cur)\nreturn result","steps":[{"id":"n-splice","title":"Splice the new interval into place","codeLine":6,"summary":"intervals = [[1,3],[6,9]], newInterval = [2,5]. The scan reaches [6,9], the first interval starting after 2, so [2,5] is spliced in just before it. combined is now [[1,3],[2,5],[6,9]].","state":{"rows":[{"label":"combined","values":[[1,3],[2,5],[6,9]],"changed":[1]}]}},{"id":"n-rest","title":"The rest of the list is copied over","codeLine":8,"summary":"Every other interval is appended into combined unchanged, so a whole second list now holds [[1,3],[2,5],[6,9]] even though only one value moved.","state":{"rows":[{"label":"combined","values":[[1,3],[2,5],[6,9]],"changed":[0,2]}]}},{"id":"n-merge","title":"Sweep the combined list, fusing neighbors","codeLine":15,"summary":"[1,3] starts result. [2,5] starts at 2, within the previous end 3, so it fuses to [1,5]. [6,9] starts past 5, so it lands on its own. result is [[1,5],[6,9]].","state":{"rows":[{"label":"result","values":[[1,5],[6,9]],"changed":[0,1]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const combined = [];\nlet placed = false;\nfor (let k = 0; k < intervals.length; k++) {\n    let cur = intervals[k];\n    if (!placed && newInterval[0] < cur[0]) {\n        combined.push(newInterval);\n        placed = true;\n    }\n    combined.push(cur);\n}\nif (!placed) {\n    combined.push(newInterval);\n}\nconst result = [];\nfor (let k = 0; k < combined.length; k++) {\n    let cur = combined[k];\n    if (result.length > 0 && cur[0] <= result[(result.length - 1)][1]) {\n        const last = result[(result.length - 1)];\n        last[1] = Math.max(last[1], cur[1]);\n    } else {\n        result.push(cur);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":21,"19":24},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13},"18":{"startLine":21,"endLine":23}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const combined: Array<Array<number>> = [];\nlet placed = false;\nfor (let k = 0; k < intervals.length; k++) {\n    let cur = intervals[k];\n    if (!placed && newInterval[0] < cur[0]) {\n        combined.push(newInterval);\n        placed = true;\n    }\n    combined.push(cur);\n}\nif (!placed) {\n    combined.push(newInterval);\n}\nconst result: Array<Array<number>> = [];\nfor (let k = 0; k < combined.length; k++) {\n    let cur = combined[k];\n    if (result.length > 0 && cur[0] <= result[(result.length - 1)][1]) {\n        const last = result[(result.length - 1)];\n        last[1] = Math.max(last[1], cur[1]);\n    } else {\n        result.push(cur);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":21,"19":24},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13},"18":{"startLine":21,"endLine":23}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> combined = new ArrayList<>();\nboolean placed = false;\nfor (int k = 0; k < intervals.size(); k++) {\n    List<Integer> cur = intervals.get(k);\n    if ((!placed && newInterval.get(0) < cur.get(0))) {\n        combined.add(newInterval);\n        placed = true;\n    }\n    combined.add(cur);\n}\nif (!placed) {\n    combined.add(newInterval);\n}\nList<List<Integer>> result = new ArrayList<>();\nfor (int k = 0; k < combined.size(); k++) {\n    List<Integer> cur = combined.get(k);\n    if ((!result.isEmpty() && cur.get(0) <= result.get((result.size() - 1)).get(1))) {\n        List<Integer> last = result.get((result.size() - 1));\n        last.set(1, Math.max(last.get(1), cur.get(1)));\n    } else {\n        result.add(cur);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":21,"19":24},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13},"18":{"startLine":21,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> combined = new();\nbool placed = false;\nfor (int k = 0; k < intervals.Count; k++) {\n    List<int> cur = intervals[k];\n    if (!placed && newInterval[0] < cur[0]) {\n        combined.Add(newInterval);\n        placed = true;\n    }\n    combined.Add(cur);\n}\nif (!placed) {\n    combined.Add(newInterval);\n}\nList<List<int>> result = new();\nfor (int k = 0; k < combined.Count; k++) {\n    List<int> cur = combined[k];\n    if (result.Count > 0 && cur[0] <= result[result.Count - 1][1]) {\n        List<int> last = result[result.Count - 1];\n        last[1] = Math.Max(last[1], cur[1]);\n    } else {\n        result.Add(cur);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":21,"19":24},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13},"18":{"startLine":21,"endLine":23}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> combined;\nbool placed = false;\nfor (int k = 0; k < intervals.size(); k++) {\n    vector<int> cur = intervals[k];\n    if ((!placed && new_interval[0] < cur[0])) {\n        combined.push_back(new_interval);\n        placed = true;\n    }\n    combined.push_back(cur);\n}\nif (!placed) {\n    combined.push_back(new_interval);\n}\nvector<vector<int>> result;\nfor (int k = 0; k < combined.size(); k++) {\n    vector<int> cur = combined[k];\n    if ((!result.empty() && cur[0] <= result[(result.size() - 1)][1])) {\n        vector<int>& last = result[(result.size() - 1)];\n        last[1] = max(last[1], cur[1]);\n    } else {\n        result.push_back(cur);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":21,"19":24},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13},"18":{"startLine":21,"endLine":23}}}}},"body":["Scan to splice the new interval into a fresh list, then sweep that list fusing each interval into the previous one when they touch."]},{"id":"sort-cost","chapter":"The problem","kind":"case-probe","eyebrow":"Count the cost","title":"What is the rebuild costing here?","summary":"The intervals arrived sorted and non-overlapping, and the code walks them once to build a whole new list, then walks that list again to merge.","workspacePanel":"trace","options":[{"id":"two-passes-rebuild","label":"Two full walks and a second copy of the list, when one walk already knows everything","rationale":"The splice walk and the merge walk each touch every interval, and a fresh combined list is allocated in between. The input was already sorted, so one walk could place and fuse in a single go.","isCorrect":true},{"id":"splice-quadratic","label":"The splice is quadratic because inserting shifts everything","rationale":"This version appends into a new list rather than shifting in place, so the splice is linear. The waste is doing two linear passes and a rebuild instead of one pass.","isCorrect":false},{"id":"merge-needed","label":"Nothing, the second sweep is doing the real work","rationale":"The merge sweep is necessary, but feeding it from a rebuilt list means a second full pass. A single pass over the original could merge as it places the new interval.","isCorrect":false}],"answer":"Two full passes and a throwaway list. The splice walk builds a fresh combined list, then the merge walk rebuilds again, even though the input came pre-sorted and non-overlapping. If that order is enough to place the new interval and fuse neighbors in one walk, the rebuild and the second pass both vanish. That is the cost to beat."},{"id":"three-regions","chapter":"The idea","kind":"case-probe","eyebrow":"Use the order","title":"How does the sorted list sit around the new interval?","summary":"intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8].","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[[1,2],[3,5],[6,7],[8,10],[12,16]]},{"label":"newInterval","values":[[4,8]],"changed":[0]}]}}]},"options":[{"id":"three-blocks","label":"A block that ends before it, a block it touches, then a block that starts after it","rationale":"Because the list is sorted and non-overlapping, every interval ending before 4 comes first, the ones touching [4,8] sit together in the middle, and everything starting after 8 follows. Three contiguous blocks, in order.","isCorrect":true},{"id":"scattered","label":"Touching intervals can be scattered anywhere in the list","rationale":"Sorted and non-overlapping means an interval that touches [4,8] cannot have a non-touching one wedged between it and the others. The overlapping ones are one solid run.","isCorrect":false},{"id":"at-most-one","label":"At most one interval can ever touch the new one","rationale":"[4,8] reaches across [3,5], [6,7], and [8,10] all at once. A wide new interval can swallow a whole run of neighbors.","isCorrect":false}],"answer":"The list splits into three contiguous blocks: intervals that end before the new one starts, the run it overlaps, and intervals that start after it ends. Walk left to right and you cross those blocks once each, in order, so a single pass copies the first block, fuses the middle into the new interval, and copies the last block. No re-sorting needed."},{"id":"merge-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Name the fusion","title":"When two intervals touch, what is their fused span?","summary":"The tracked interval is [4,8] and the overlapping neighbor is [3,5].","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"newInterval","values":[[4,8]],"changed":[0]},{"label":"current","values":[[3,5]],"changed":[0]}]}}]},"options":[{"id":"min-max","label":"The smaller of the two starts to the larger of the two ends, so [3,8]","rationale":"The fused interval has to cover both, so its start is the lower start (3) and its end is the higher end (8). That keeps the widest reach of either side.","isCorrect":true},{"id":"take-newest","label":"Replace it with the neighbor, [3,5]","rationale":"Overwriting with the neighbor would drop the new interval's reach out to 8. The fusion must keep whichever end is further out.","isCorrect":false},{"id":"extend-end-only","label":"Keep the start at 4 and stretch the end, [4,8]","rationale":"Holding the start at 4 loses the neighbor's earlier start of 3. The fused span has to reach back to the lower start too.","isCorrect":false}],"answer":"Lower start, higher end: [3,8]. Fusing means the result must cover both intervals, so the tracked start drops to the smaller start and the tracked end rises to the larger end. Each neighbor in the overlapping run gets folded in this way, and the tracked interval only ever grows."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"How should we place the new interval?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[[1,2],[3,5],[6,7],[8,10],[12,16]]},{"label":"newInterval","values":[[4,8]],"changed":[0]}]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"One cursor, three phases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[[1,2],[3,5],[6,7],[8,10]]},{"label":"newInterval","values":[[4,8]],"changed":[0]},{"label":"result","values":[]}]}}]},"body":["A single cursor walks intervals = [[1,2],[3,5],[6,7],[8,10]] from the left while the tracked interval starts as newInterval = [4,8] and result starts empty.","First it copies intervals that end before 4 into result. Then it fuses every interval that touches the tracked one, growing the tracked span. Finally it drops the tracked interval in and copies whatever remains."]},{"id":"trace","chapter":"Trace","kind":"dry-run","eyebrow":"Predict the moves","title":"Walk the insert end to end","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"b-copy","state":{"arrays":[{"name":"intervals","values":[[1,2],[3,5],[6,7],[8,10]],"i":0},{"name":"newInterval","values":[[4,8]]},{"name":"result","values":[]}]}},{"id":"b-fuse-start","state":{"arrays":[{"name":"intervals","values":[[1,2],[3,5],[6,7],[8,10]],"i":1},{"name":"newInterval","values":[[4,8]]},{"name":"result","values":[[1,2]]}]}},{"id":"b-touch-end","state":{"arrays":[{"name":"intervals","values":[[1,2],[3,5],[6,7],[8,10]],"i":3},{"name":"newInterval","values":[[3,8]]},{"name":"result","values":[[1,2]]}]}},{"id":"b-drop","state":{"arrays":[{"name":"intervals","values":[[1,2],[3,5],[6,7],[8,10]]},{"name":"newInterval","values":[[3,10]]},{"name":"result","values":[[1,2]]}]}}]},"beats":[{"id":"b-copy","title":"The cursor sits on [1,2]. What happens to it?","prompt":"[1,2] ends at 2, below the new interval's start of 4.","options":[{"id":"copy","label":"Copy it straight into result","rationale":"It ends at 2, before the new interval starts at 4, so it can never touch it. It goes into result unchanged.","isCorrect":true},{"id":"fuse","label":"Fuse it into the tracked interval","rationale":"Fusing is for intervals that reach the new one. [1,2] ends at 2, well short of 4, so there is nothing to fuse.","isCorrect":false},{"id":"stop","label":"Stop and return result","rationale":"There are still intervals ahead that will touch [4,8]. Returning now would drop them.","isCorrect":false}],"answer":"Copied as is. [1,2] ends before the new interval starts, so it belongs to the first block and is placed into result untouched."},{"id":"b-fuse-start","title":"Now [3,5] touches the tracked [4,8]. What does the tracked span become?","prompt":"[3,5] starts at 3, at or below the tracked end of 8, so it overlaps.","options":[{"id":"lower-start","label":"Its start drops to 3 while the end stays 8, giving [3,8]","rationale":"The lower start (3) and the higher end (8) keep the widest reach, so the tracked interval grows leftward to [3,8].","isCorrect":true},{"id":"become-35","label":"It becomes [3,5], the touching interval","rationale":"Overwriting with [3,5] would throw away the reach out to 8. The fusion keeps the larger end.","isCorrect":false},{"id":"copy-35","label":"[3,5] is copied into result on its own","rationale":"[3,5] overlaps the tracked interval, so it must fuse in rather than land separately, or the result would overlap.","isCorrect":false}],"answer":"[3,8]. The start drops to the smaller start 3 and the end holds at the larger end 8, so the tracked interval reaches back to 3."},{"id":"b-touch-end","title":"After [6,7] folds in, does [8,10] touch the tracked interval?","prompt":"[6,7] already folded in without changing the end. The tracked interval is [3,8] and the next interval [8,10] starts at 8.","options":[{"id":"merge-touch","label":"Yes, 8 is not past 8, so it fuses and the end rises to 10","rationale":"A start equal to the tracked end still counts as touching, so [8,10] fuses and the end stretches to 10, giving [3,10].","isCorrect":true},{"id":"strict-gap","label":"No, they only share a single point, so leave it","rationale":"Sharing the endpoint 8 means they meet, and the problem fuses intervals that touch. Treating 8 as a gap would split one interval into two.","isCorrect":false},{"id":"copy-810","label":"Copy [8,10] into result separately","rationale":"[8,10] touches the tracked interval at 8, so it has to fuse in, not land on its own.","isCorrect":false}],"answer":"It fuses. A start equal to the tracked end still touches, so [8,10] folds in and the tracked interval grows to [3,10]."},{"id":"b-drop","title":"The scan has no intervals left. What goes into result now?","prompt":"The overlapping run is exhausted and the tracked interval is [3,10].","options":[{"id":"append-tracked","label":"Drop the tracked [3,10] in after the copied [1,2]","rationale":"The fused interval is complete, so it lands in result after [1,2], giving [[1,2],[3,10]] in sorted order.","isCorrect":true},{"id":"discard","label":"Discard the tracked interval, it was only scratch space","rationale":"The tracked interval is the whole point: it carries every fused neighbor and must be placed into result.","isCorrect":false},{"id":"resort","label":"Sort result before returning","rationale":"result was built left to right in sorted order already, so a second sort would only repeat the cost we set out to avoid.","isCorrect":false}],"answer":"The tracked [3,10] drops into result after [1,2]. With no intervals left to copy, result is [[1,2],[3,10]], sorted and non-overlapping."}]},{"id":"shrink-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could fusing just stretch the end?","summary":"Folding a neighbor in by raising the end alone looks complete, and it passes every case where the new interval already starts first. But it never lowers the start. Watch a neighbor that begins earlier than the new interval.","workspacePanel":"trace","pitfall":"The merge loop below fuses overlapping intervals, but it only ever raises the tracked end and leaves the tracked start untouched.","whyItMatters":"When an overlapping neighbor starts before the new interval, the fused interval has to reach back to that earlier start. Updating the end alone strands the lower start, so the result loses coverage on the left. The fusion must lower the start with the smaller value too.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\ni = 0\nn = len(intervals)\nwhile i < n and intervals[i][1] < newInterval[0]:\n    result.append(intervals[i])\n    i += 1\nwhile i < n and intervals[i][0] <= newInterval[1]:\n    newInterval[1] = max(newInterval[1], intervals[i][1])\n    i += 1\nresult.append(newInterval)","steps":[{"id":"p-start","title":"A neighbor that starts earlier","codeLine":8,"summary":"intervals = [[1,5]], newInterval = [2,8]. The overlap loop reaches [1,5], which starts at 1, below the tracked start of 2, so it counts as overlapping.","state":{"rows":[{"label":"intervals","values":[[1,5]],"changed":[0]},{"label":"newInterval","values":[[2,8]],"changed":[0]}]}},{"id":"p-end-only","title":"Only the end is touched","codeLine":9,"summary":"max(8, 5) is 8, so the end stays 8 and the start stays 2. The tracked interval is still [2,8], even though [1,5] reached back to 1.","state":{"rows":[{"label":"intervals","values":[[1,5]],"changed":[0]},{"label":"newInterval","values":[[2,8]],"changed":[0]}]}},{"id":"p-wrong","title":"The 1 is gone","codeLine":10,"summary":"result gets [2,8], so the answer is [[2,8]]. But [1,5] covered 1, and the correct result is [[1,8]]. The left edge was dropped.","state":{"rows":[{"label":"result","values":[[2,8]],"changed":[0]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nlet i = 0;\nconst n = intervals.length;\nwhile ((i < n) && (intervals[i][1] < newInterval[0])) {\n    result.push(intervals[i]);\n    i++;\n}\nwhile ((i < n) && (intervals[i][0] <= newInterval[1])) {\n    newInterval[1] = Math.max(newInterval[1], intervals[i][1]);\n    i++;\n}\nresult.push(newInterval);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"6":{"startLine":6,"endLine":7},"9":{"startLine":10,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<number>> = [];\nlet i = 0;\nconst n = intervals.length;\nwhile ((i < n) && (intervals[i][1] < newInterval[0])) {\n    result.push(intervals[i]);\n    i++;\n}\nwhile ((i < n) && (intervals[i][0] <= newInterval[1])) {\n    newInterval[1] = Math.max(newInterval[1], intervals[i][1]);\n    i++;\n}\nresult.push(newInterval);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"6":{"startLine":6,"endLine":7},"9":{"startLine":10,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> result = new ArrayList<>();\nint i = 0;\nint n = intervals.size();\nwhile ((i < n && intervals.get(i).get(1) < newInterval.get(0))) {\n    result.add(intervals.get(i));\n    i++;\n}\nwhile ((i < n && intervals.get(i).get(0) <= newInterval.get(1))) {\n    newInterval.set(1, Math.max(newInterval.get(1), intervals.get(i).get(1)));\n    i++;\n}\nresult.add(newInterval);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"6":{"startLine":6,"endLine":7},"9":{"startLine":10,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> result = new();\nint i = 0;\nint n = intervals.Count;\nwhile (i < n && intervals[i][1] < newInterval[0]) {\n    result.Add(intervals[i]);\n    i++;\n}\nwhile (i < n && intervals[i][0] <= newInterval[1]) {\n    newInterval[1] = Math.Max(newInterval[1], intervals[i][1]);\n    i++;\n}\nresult.Add(newInterval);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"6":{"startLine":6,"endLine":7},"9":{"startLine":10,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> result;\nint i = 0;\nint n = intervals.size();\nwhile ((i < n && intervals[i][1] < new_interval[0])) {\n    result.push_back(intervals[i]);\n    i++;\n}\nwhile ((i < n && intervals[i][0] <= new_interval[1])) {\n    new_interval[1] = max(new_interval[1], intervals[i][1]);\n    i++;\n}\nresult.push_back(new_interval);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"6":{"startLine":6,"endLine":7},"9":{"startLine":10,"endLine":11}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"Two inputs leave one of the three blocks empty.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[[1,5]]},{"label":"newInterval","values":[[6,8]],"changed":[0]},{"label":"result","values":[]}]}}]},"body":["Two inputs each empty out a block: a list with no intervals at all, and a new interval that starts after everything else so the overlapping run is empty.","Whether the one pass already handles each one or needs care is what the next two screens decide."]},{"id":"empty-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"No intervals","title":"What does the pass return when there are no intervals?","summary":"intervals = [], newInterval = [5,7].","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[]},{"label":"newInterval","values":[[5,7]],"changed":[0]},{"label":"result","values":[]}]}}]},"options":[{"id":"just-new","label":"Just the new interval, [[5,7]]","rationale":"Every loop sees an empty list and does nothing, so the tracked interval is dropped in untouched and result is [[5,7]].","isCorrect":true},{"id":"empty-out","label":"An empty list, since there was nothing to scan","rationale":"The new interval still has to be placed. Dropping it in after the loops is unconditional, so the result is never empty.","isCorrect":false},{"id":"crash","label":"It fails because there is no interval to compare against","rationale":"Each loop guard checks the cursor against the length first, so an empty list just skips every loop body without ever indexing into it.","isCorrect":false}],"answer":"It returns [[5,7]]. All three loops see an empty list and skip, then the new interval is dropped into result regardless. Placing the new interval after the loops, not inside them, is what makes the empty case fall out for free."},{"id":"after-all-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"After everything","title":"Where does a new interval past the end land?","summary":"intervals = [[1,5]], newInterval = [6,8].","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[[1,5]],"changed":[0]},{"label":"newInterval","values":[[6,8]],"changed":[0]},{"label":"result","values":[]}]}}]},"options":[{"id":"copy-then-new","label":"[1,5] is copied first, then [6,8] is dropped in, giving [[1,5],[6,8]]","rationale":"[1,5] ends at 5, before 6, so the first loop copies it. Nothing overlaps, so the tracked [6,8] is dropped in afterward, and the order stays sorted.","isCorrect":true},{"id":"new-lost","label":"Only [[1,5]], because the overlap loop never runs","rationale":"The new interval is dropped in after the loops no matter what, so an empty overlap run does not lose it.","isCorrect":false},{"id":"new-first","label":"[[6,8],[1,5]], with the new interval first","rationale":"The first loop copies [1,5] before the new interval is placed, so [6,8] lands after it and the result stays sorted by start.","isCorrect":false}],"answer":"[[1,5],[6,8]]. The first loop copies every interval ending before 6, the overlap loop finds nothing to fuse, and the tracked [6,8] is dropped in last. Copying the before-block first is what keeps an end-of-list interval in sorted order."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"One cursor, three phases, and a fusion that moves both edges.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"rows":[{"label":"intervals","values":[[1,2],[3,5],[6,7],[8,10]]},{"label":"newInterval","values":[[4,8]],"changed":[0]},{"label":"result","values":[]}]}}]},"body":["Start a fresh result list and a cursor at the front. First copy every interval that ends before the new interval starts. Then, while the current interval touches the tracked one, fuse it in by pulling the tracked start down to the lower start and pushing the tracked end up to the higher end. Drop the tracked interval into result, then copy whatever intervals remain. The subtlety to keep in mind is that touching counts as overlap, so the second phase must include an interval that starts exactly at the tracked end."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the insert-and-fuse pass","eyebrow":"Build the solution","summary":"Copy the before-block, fuse the overlapping run by moving both edges, then drop in the tracked interval and copy the rest.","workspacePanel":"code","checkpoints":[{"id":"init-result","title":"Set up result state","description":"Create an empty output list before scanning intervals.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-empty-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Trying to mutate intervals in place without tracking output order","Seeding the output with newInterval before its position is known"],"hint":"Start with an empty result list.","semanticSpec":{"intent":"Initialize the result sequence that will receive intervals in final order.","doneWhen":"This step is done when a result list exists before append and return operations.","shouldFailWhen":"This step should fail if no result sequence is initialized.","roles":["result sequence"],"mustProve":["An empty result sequence is initialized before scan output is appended."],"mustNotAccept":["Only declaring scalar cursor variables.","Returning the input list directly."],"equivalentVariants":["Use `result = []` before scanning."],"proofSnippets":[{"id":"py-insert-interval-init","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        return result"}]}},{"id":"scan-intervals","title":"Scan the sorted intervals","description":"Walk through the interval list with one cursor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Using nested pairwise merging","Restarting the scan after each merge"],"hint":"Keep one index and advance it as intervals are copied or merged.","semanticSpec":{"intent":"Scan the interval input once in sorted order.","doneWhen":"This step is done when the implementation loops over the interval input with a cursor.","shouldFailWhen":"This step should fail if the code never scans the interval sequence.","roles":["interval sequence","scan cursor"],"mustProve":["The code scans the interval sequence.","The scan exposes the current interval for later decisions."],"mustNotAccept":["Returning a constant interval list.","Only sorting without scanning."],"equivalentVariants":["Use `while i < n` loops with one cursor.","Use an equivalent single pass through intervals."],"proofSnippets":[{"id":"py-insert-interval-scan","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            i += 1\n        return 0"}]}},{"id":"append-disjoint","title":"Copy disjoint intervals","description":"Append intervals that do not overlap the new interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"appends_scan_state_to_result","scope":"append-disjoint-regions","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Dropping intervals that come before the new interval","Forgetting to append intervals that come after the new interval"],"hint":"Intervals ending before the new start can be appended immediately.","semanticSpec":{"intent":"Append scanned interval values into the result sequence.","doneWhen":"This step is done when scan items can be copied into the output result.","shouldFailWhen":"This step should fail if scanned intervals are never appended to the result.","roles":["current interval","result sequence"],"mustProve":["The result sequence receives values from the interval scan."],"mustNotAccept":["Only updating newInterval.","Returning without copying scanned intervals."],"equivalentVariants":["Use `result.append(intervals[i])` for intervals outside the overlap region."],"proofSnippets":[{"id":"py-insert-interval-append","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        return 0"}]}},{"id":"check-overlap","title":"Detect overlapping intervals","description":"Continue merging while the current interval starts at or before the merged new interval ends.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"branches_on_interval_overlap","scope":"check-touching-overlap","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Using < instead of <= and missing touching intervals","Comparing against the wrong endpoint"],"hint":"An interval overlaps when `intervals[i][0] <= newInterval[1]`.","semanticSpec":{"intent":"Branch or continue based on interval overlap against the tracked merged interval.","doneWhen":"This step is done when current interval start is compared against the tracked interval end.","shouldFailWhen":"This step should fail if overlap is not tested against the interval end.","roles":["current interval","tracked interval","overlap branch"],"mustProve":["The scan checks current start against the tracked interval end.","The condition controls the merge region."],"mustNotAccept":["Checking only interval length.","Appending every interval without overlap logic."],"equivalentVariants":["Use `while i < n and intervals[i][0] <= newInterval[1]`.","Use an equivalent overlap condition around a merge branch."],"proofSnippets":[{"id":"py-insert-interval-overlap-check","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            i += 1\n        result.append(newInterval)\n        return 0"}]}},{"id":"merge-overlaps","title":"Expand the merged interval","description":"Absorb each overlapping interval by updating both bounds of the new interval.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"expands_tracked_interval_bounds_on_overlap","scope":"merge-overlap","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Only updating the end and losing intervals that start earlier","Setting the end directly to the current end and shrinking coverage"],"hint":"Use min for the start and max for the end.","semanticSpec":{"intent":"Merge overlapping intervals into the tracked new interval by expanding both bounds.","doneWhen":"This step is done when overlap handling updates the tracked start from min and tracked end from max.","shouldFailWhen":"This step should fail if overlap handling only updates one bound or can shrink coverage.","roles":["tracked interval","current interval","bound expansion"],"mustProve":["The overlap region updates the tracked start with the current interval.","The overlap region updates the tracked end with the current interval."],"mustNotAccept":["Updating only the end.","Appending overlapping intervals separately.","Replacing bounds without preserving the wider coverage."],"equivalentVariants":["Use `newInterval[0] = min(newInterval[0], intervals[i][0])` and `newInterval[1] = max(newInterval[1], intervals[i][1])`."],"proofSnippets":[{"id":"py-insert-interval-merge","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            newInterval[0] = min(newInterval[0], intervals[i][0])\n            newInterval[1] = max(newInterval[1], intervals[i][1])\n            i += 1\n        result.append(newInterval)\n        return 0"}]}},{"id":"return-result","title":"Return final interval list","description":"Return the result sequence after all before, merged, and after intervals are included.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning newInterval only","Returning intervals without the inserted interval"],"hint":"Return the result list after appending the merged new interval and the suffix intervals.","semanticSpec":{"intent":"Return the built result sequence.","doneWhen":"This step is done when the terminal return is the result list populated during the scan.","shouldFailWhen":"This step should fail if the code returns a scalar, the original input, or only the new interval.","roles":["result sequence","terminal return"],"mustProve":["The result sequence is returned after scan appends."],"mustNotAccept":["Returning `newInterval`.","Returning `intervals` directly.","Returning before overlap processing."],"equivalentVariants":["Return `result` after all scanning is complete."],"proofSnippets":[{"id":"py-insert-interval-return","language":"python","code":"class Solution:\n    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n        result = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            result.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            newInterval[0] = min(newInterval[0], intervals[i][0])\n            newInterval[1] = max(newInterval[1], intervals[i][1])\n            i += 1\n        result.append(newInterval)\n        while i < n:\n            result.append(intervals[i])\n            i += 1\n        return result"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"A sorted, non-overlapping list lets one pass place the new interval without ever re-sorting.","workspacePanel":"code","body":["The given order is the whole gift. Sorted and non-overlapping means the new interval splits the list into a before-block, an overlapping run, and an after-block, each a single contiguous stretch, so one left-to-right pass crosses them in order.","Fusing keeps the widest reach: the tracked start drops to the lower start and the tracked end rises to the higher end, folding in every neighbor the new interval touches."],"takeaways":[{"title":"Three blocks, one pass","body":"A sorted, non-overlapping list puts the before, overlapping, and after intervals in three contiguous stretches, so a single scan handles each in turn with no re-sorting."},{"title":"Fuse by moving both edges","body":"Each touching neighbor lowers the tracked start to the smaller start and raises the tracked end to the larger end, so the fused interval always covers both."},{"title":"Touching counts as overlap","body":"A neighbor that starts exactly at the tracked end still meets it, so the overlap test allows equality or the result splits one interval into two."}],"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","secondaryParam":"newInterval","sizeMetric":"length","constraints":["sorted"]}}
