{"id":"range-addition","title":"Range Addition","difficulty":"medium","patterns":["prefix-sum"],"primaryConcept":"array-prefix-sum-basics","concepts":["array-prefix-sum-basics"],"problemForm":"core","companies":["Google","Meta"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"range-updates","primaryParam":"updates","sizeMetric":"length","sizes":[8,16,32]},"description":"You are given an integer `length` and a list of updates. Each update `[start, end, inc]` adds `inc` to every index from `start` through `end`, inclusive. Return the array after applying all updates.","examples":[{"input":"length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]","output":"[-2,0,3,5,3]","explanation":"The first update adds 2 to indices 1 through 3, the second adds 3 to indices 2 through 4, and the third subtracts 2 from indices 0 through 2."},{"input":"length = 6, updates = [[0,5,1],[1,4,2],[2,3,3]]","output":"[1,3,6,6,3,1]","explanation":"Nested ranges stack on top of one another, so the middle receives all three increments."}],"constraints":[{"id":"length-range","text":"1 <= length <= 10^5","check":{"kind":"valueRange","target":"length","selector":"value","min":1,"max":100000}},{"id":"updates-count","text":"0 <= len(updates) <= 10^5","check":{"kind":"sizeRange","target":"updates","measure":"arrayLength","min":0,"max":100000}},{"id":"update-shape","text":"len(updates[i]) == 3","check":{"kind":"shape","target":"updates","shape":"tupleArray","tupleLength":3}},{"id":"update-bounds","text":"0 <= start <= end < length","check":{"kind":"relation","relation":"rangeUpdateBounds","updates":"updates","length":"length"}},{"id":"update-increment-range","text":"-10^4 <= inc <= 10^4","check":{"kind":"valueRange","target":"updates","selector":"tupleItemsAtIndex","index":2,"min":-10000,"max":10000}}],"starterCode":"class Solution:\n    def getModifiedArray(self, length: int, updates: list[list[int]]) -> list[int]:\n        # Your code here\n        pass","functionName":"getModifiedArray","testCases":[{"id":"1","input":{"length":5,"updates":[[1,3,2],[2,4,3],[0,2,-2]]},"expected":[-2,0,3,5,3],"description":"Canonical overlapping positive and negative updates."},{"id":"2","input":{"length":6,"updates":[[0,5,1],[1,4,2],[2,3,3]]},"expected":[1,3,6,6,3,1],"description":"Nested ranges accumulate in the center."},{"id":"3","input":{"length":1,"updates":[[0,0,5],[0,0,-2]]},"expected":[3],"description":"Single element receives multiple updates."},{"id":"4","input":{"length":4,"updates":[]},"expected":[0,0,0,0],"description":"No updates leaves a zero array."},{"id":"h1","input":{"length":3,"updates":[[0,2,1]]},"expected":[1,1,1],"description":"Full range update has no right boundary inside the array."},{"id":"h2","input":{"length":5,"updates":[[0,0,4],[4,4,7],[1,3,2]]},"expected":[4,2,2,2,7],"description":"Boundary-only updates at both ends."},{"id":"h3","input":{"length":6,"updates":[[2,5,3],[0,1,2],[1,4,-1]]},"expected":[2,1,2,2,2,3],"description":"Mixed positive and negative overlapping ranges."},{"id":"h4","input":{"length":5,"updates":[[0,4,10],[1,3,-5],[2,2,7]]},"expected":[10,5,12,5,10],"description":"Single-index update inside a negative subrange."},{"id":"h5","input":{"length":2,"updates":[[0,0,1],[1,1,2],[0,1,3]]},"expected":[4,5],"description":"Short array with endpoint and full-range updates."},{"id":"h6","input":{"length":3,"updates":[[1,2,-3]]},"expected":[0,-3,-3],"description":"A single negative range update touches only the suffix."},{"id":"h7","input":{"length":7,"updates":[[0,6,1],[1,3,2],[2,5,-1],[4,4,5],[0,0,-3]]},"expected":[-2,3,2,2,5,0,1],"description":"Five overlapping updates combine full-range, middle, single-index, and endpoint deltas."},{"id":"topup-wide-and-tail-updates","input":{"length":8,"updates":[[0,7,2],[3,5,-4],[6,7,1]]},"expected":[2,2,2,-2,-2,-2,3,3],"description":"Wide update with a negative middle segment and positive tail adjustment."}],"hints":[{"level":1,"content":"A range update only changes where the increment starts and where it stops affecting later positions.","revealPattern":false},{"level":2,"content":"Use a difference array: add `inc` at `start`, and subtract `inc` at `end + 1` when that index exists.","revealPattern":true},{"level":3,"content":"After all boundary updates, take a running prefix sum over the difference array to recover the final values.","revealPattern":true}],"guidedFlow":{"version":2,"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":"apply-every-index","name":"Update every covered index","summary":"For each update, loop from `start` to `end` and add `inc` directly.","decisionReason":"A wide update re-walks the same `length` cells, and many updates re-walk them again, so the cost climbs to `O(length * updates)`.","complexity":{"time":"O(length * updates)","space":"O(length)"},"tradeoffs":["Runs in O(length * updates) time and uses O(length) space."],"isOptimal":false},{"id":"difference-array","name":"Boundary deltas plus sweep","summary":"Record only where each range starts and stops, then sweep once to materialize the final array.","decisionReason":"Each update writes just two boundary marks in constant time, and one final sweep expands them, giving `O(length + updates)` no matter how wide the ranges are.","complexity":{"time":"O(length + updates)","space":"O(length)"},"tradeoffs":["Runs in O(length + updates) time and uses O(length) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-diff","title":"Initialize the difference array","description":"Create a zero-filled array that will store boundary changes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"initializes_boundary_state","scope":"init-boundary","readMode":"sweep-line-value-query-v1"}]},"commonMistakes":["Starting from the input updates instead of an output-sized array","Creating an array with the wrong length"],"hint":"The boundary state should have one slot for each output index.","semanticSpec":{"intent":"Initialize dense boundary state for a diff-array sweep.","doneWhen":"A zero-filled boundary array exists before applying updates.","shouldFailWhen":"This step should fail if no boundary state is initialized.","roles":["difference array"],"mustProve":["The solution initializes sweep-line boundary state."],"mustNotAccept":["Updating the final output in every range without boundary state."]}},{"id":"apply-deltas","title":"Apply paired boundary deltas","description":"For each update, add at `start` and subtract at `end + 1` when that boundary is inside the array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"applies_boundary_deltas","scope":"apply-deltas","readMode":"sweep-line-value-query-v1"}]},"commonMistakes":["Forgetting the negative boundary","Subtracting at `end` instead of `end + 1`","Writing past the end of the array"],"hint":"The positive boundary starts the increment; the negative boundary stops it after `end`.","semanticSpec":{"intent":"Record paired positive and negative boundary deltas.","doneWhen":"The update loop writes both entering and leaving deltas to the boundary state.","shouldFailWhen":"This step should fail if only one side of the range is marked.","roles":["start boundary","end boundary","difference array"],"mustProve":["The solution applies paired boundary deltas."],"mustNotAccept":["Only adding at the start boundary."]}},{"id":"sweep-values","title":"Sweep the boundary array","description":"Scan the difference array in order while carrying the active running total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"performs_ordered_sweep","scope":"sweep-values","readMode":"sweep-line-value-query-v1"}]},"commonMistakes":["Returning the raw difference array","Resetting the running total on every index"],"hint":"Each index's final value is the running sum of all boundary changes up to that index.","semanticSpec":{"intent":"Perform an ordered accumulation sweep over boundary state.","doneWhen":"The code scans the boundary array and updates a carried running value.","shouldFailWhen":"This step should fail if no ordered sweep happens after updates.","roles":["running total","difference array"],"mustProve":["The solution performs an ordered sweep."],"mustNotAccept":["Returning boundary deltas without accumulating them."]}},{"id":"write-output","title":"Write accumulated values","description":"Store the running total back into the dense result position during the sweep.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"writes_dense_sweep_output","scope":"write-output","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Computing the running total but never saving it","Appending values in a different order than the array indices"],"hint":"After adding `diff[i]` into the running total, write that total as the final value at `i`.","semanticSpec":{"intent":"Materialize the dense output from the running sweep value.","doneWhen":"The sweep writes the accumulated running value into the dense state.","shouldFailWhen":"This step should fail if the sweep total is not written to output.","roles":["running total","output array"],"mustProve":["The solution writes the dense sweep output."],"mustNotAccept":["Only tracking a scalar total without storing final values."]}},{"id":"return-result","title":"Return the final array","description":"Return the dense array after all boundary deltas have been swept.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"returns_sweep_result","scope":"return-answer","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Returning the updates list","Returning a fresh empty array","Returning before the sweep"],"hint":"The diff array has become the final array after the sweep, so return it.","semanticSpec":{"intent":"Return the completed dense sweep result.","doneWhen":"The terminal return uses the swept output state.","shouldFailWhen":"This step should fail if the return ignores the swept state.","roles":["output array"],"mustProve":["The solution returns the sweep result."],"mustNotAccept":["Returning an unrelated array."]}}],"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Apply the ranges, return the array","workspacePanel":"problem","body":["Start from an array of `length` zeros. Each update [start, end, inc] adds inc to every index from start through end, inclusive. After every update is applied, return the array.","The obvious way is to do exactly what the problem says, range by range. Watch it work, then count the cost."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Add inc across every covered index","summary":"It returns the right array. Watch each update walk its whole span, one index at a time.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = [0] * length\nfor start, end, inc in updates:\n    for i in range(start, end + 1):\n        result[i] += inc\nreturn result","steps":[{"id":"first-range","title":"First update fills its span","codeLine":4,"summary":"Update [1,3,2] adds 2 to indices 1, 2, and 3 one cell at a time.","state":{"nums":[0,2,2,2,0],"i":3,"labels":{"nums":"result"}}},{"id":"second-range","title":"Second update walks an overlapping span","codeLine":4,"summary":"Update [2,4,3] adds 3 to indices 2, 3, and 4. Indices 2 and 3 were already touched by the first update and get walked again.","state":{"nums":[0,2,5,5,3],"i":4,"labels":{"nums":"result"}}},{"id":"third-range","title":"Third update walks the front again","codeLine":4,"summary":"Update [0,2,-2] subtracts 2 from indices 0, 1, and 2, landing on [-2,0,3,5,3]. Index 2 has now been visited by all three updates.","state":{"nums":[-2,0,3,5,3],"i":2,"labels":{"nums":"result"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = Array(length).fill(0);\nfor (const [start, end, inc] of updates) {\n    for (let i = start; i < (end + 1); i++) {\n        result[i] = (result[i] + inc);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7},"statementBundles":{"4":{"startLine":4,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result = Array(length).fill(0);\nfor (const [start, end, inc] of updates) {\n    for (let i = start; i < (end + 1); i++) {\n        result[i] = (result[i] + inc);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7},"statementBundles":{"4":{"startLine":4,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nfor (int index = 0; index < length; index++) {\n    result.add(0);\n}\nfor (List<Integer> update : updates) {\n    int start = update.get(0);\n    int end = update.get(1);\n    int inc = update.get(2);\n    for (int i = ((Number)start).intValue(); i < (end + 1); i++) {\n        result.set(i, (result.get(i) + inc));\n    }\n}\nreturn result;","lineMap":{"1":1,"2":5,"3":9,"4":10,"5":13},"statementBundles":{"1":{"startLine":1,"endLine":4},"2":{"startLine":5,"endLine":8},"4":{"startLine":10,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = Enumerable.Repeat<int>(0, length).ToList();\nforeach (var item in updates) {\n    int start = item[0];\n    int end = item[1];\n    int inc = item[2];\n    for (int i = start; i < end + 1; i++) {\n        result[i] = result[i] + inc;\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":6,"4":7,"5":10},"statementBundles":{"2":{"startLine":2,"endLine":5},"4":{"startLine":7,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result = vector<int>(length, 0);\nfor (vector<int> item : updates) {\n    int start = item[0];\n    int end = item[1];\n    int inc = item[2];\n    for (int i = start; i < (end + 1); i++) {\n        result[i] = (result[i] + inc);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":6,"4":7,"5":10},"statementBundles":{"2":{"startLine":2,"endLine":5},"4":{"startLine":7,"endLine":9}}}}},"body":["For each update, step from start to end and add inc to every index in between."]},{"id":"cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Count the work","title":"How much work does a wide update do?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"wide-update-walk","state":{"nums":[1,1,1,0,0],"i":2,"labels":{"nums":"result"}}}]},"summary":"A single update can span the whole array, and there can be as many updates as the array is long.","options":[{"id":"length-times-updates","label":"Up to length steps per update, so about length times the number of updates","rationale":"An update covering [0, length-1] touches every index. With that many updates, the inner walk repeats the full array over and over: O(length * updates).","isCorrect":true},{"id":"constant-per-update","label":"A fixed amount per update, regardless of its width","rationale":"The inner loop runs once per covered index, so a range from 0 to length-1 costs length steps.","isCorrect":false},{"id":"just-length","label":"About length total, no matter how many updates","rationale":"Each update re-walks its span from scratch. Ten wide updates walk the array ten times; the cost scales with the number of updates too.","isCorrect":false}],"answer":"Each wide update re-walks the whole array, so the cost is O(length * updates). The same indices get rewritten by update after update."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"What is the smallest mark a single range needs?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"range-span","state":{"nums":[0,0,0,0,0],"left":1,"right":3,"labels":{"nums":"diff","left":"start","right":"end"}}}]},"quiz":{"contract":"pattern-recognition-v1","question":"What is the smallest mark a single range needs?","signalPrompt":"Adding inc from start through end changes the array in a regular way. Where does that change actually begin and end?","options":[{"id":"two-endpoints","label":"Two marks: where inc switches on at start, and where it switches off after end","signal":"Across the span the increment is constant; only its two edges differ from the neighbors outside.","rationale":"Record +inc at start and -inc just past end. A later left-to-right running total turns those two edge marks back into the full span. Every interior index is implied, never written.","isCorrect":true},{"id":"every-index","label":"One mark at every index the range covers","signal":"The range really does change every covered index.","rationale":"That is the brute force again: marking every index is exactly the per-index walk whose cost we are trying to escape.","isCorrect":false},{"id":"sorted-search","label":"Sort the updates and binary search for each index","signal":"Sorted data unlocks binary search.","rationale":"Nothing here is searched for. The updates just need to be combined, and there is no sorted target to locate.","isCorrect":false},{"id":"stack-ranges","label":"Push each range on a stack and pop overlaps","signal":"Overlapping ranges feel like nesting.","rationale":"Ranges are not resolved last-in first-out, and overlaps simply add together. A stack adds machinery the problem never asks for.","isCorrect":false}],"missFeedback":"Inside the span the change is constant. Only the start edge and the index just past end differ from their neighbors."}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"blank-array","state":{"nums":[0,0,0,0,0],"labels":{"nums":"array"}}}]}},{"id":"state-setup","chapter":"The idea","kind":"case-probe","eyebrow":"Set up the state","title":"What does each slot of the marks array hold?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-setup-state","state":{"nums":[0,2,0,0,-2],"labels":{"nums":"diff"}}}]},"summary":"After marking only update [1,3,2], the array holds 2 at index 1 and -2 at index 4. Call this array diff.","options":[{"id":"change-from-left-neighbor","label":"The step change from the index to its left","rationale":"diff[i] records how much index i differs from index i-1. The +2 at index 1 turns the increment on; the -2 at index 4 turns it off. The final values appear only after a running total.","isCorrect":true},{"id":"final-value","label":"The final value at that index","rationale":"If these were final values, index 2 and 3 would already read 2. They are still 0 because diff stores the +2 at index 1 and the -2 at index 4; the interior appears during the sweep.","isCorrect":false},{"id":"count-of-updates","label":"How many updates have touched that index","rationale":"diff carries signed increments, not visit counts. A negative mark like -2 has no meaning as a count.","isCorrect":false}],"answer":"diff[i] is the change from index i-1 to index i. Two edge marks per range, with the interior left implied."},{"id":"boundary-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"Where does the -inc that cancels a range go?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"boundary-state","state":{"nums":[0,2,0,0,-2],"current":4,"labels":{"nums":"diff"}}}]},"summary":"Update [1,3,2] adds 2 from index 1 through 3. The +2 goes at index 1.","options":[{"id":"end-plus-one","label":"At end + 1, the first index the increment should no longer reach","rationale":"The +2 must still apply at index 3 (the end), so the cancel lands at index 4. The running total carries +2 through index 3 and drops back at index 4.","isCorrect":true},{"id":"at-end","label":"At end itself, index 3","rationale":"Cancel at index 3 and the +2 never reaches index 3 at all. The increment must cover end inclusively, so the cancel belongs one slot past it.","isCorrect":false},{"id":"at-last","label":"Always at the last index of the array","rationale":"The increment stops right after end, not at the far end of the array. A range ending at index 3 must release at index 4 regardless of how long the array is.","isCorrect":false}],"answer":"The +inc goes at start and the -inc at end + 1, so the increment covers end inclusively and stops right after."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Mark the edges, then sweep","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[0,0,0,0,0],"labels":{"nums":"diff"}}}]},"body":["diff starts all zeros. First every update writes its two edge marks, then a single left-to-right pass adds up diff into the running total that becomes each final value.","Predict the marks each update leaves and the totals the sweep lands on."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the marks","title":"Trace the diff array and its sweep","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"mark-first","state":{"nums":[0,0,0,0,0],"left":1,"right":3,"labels":{"nums":"diff","left":"start","right":"end"}}},{"id":"mark-second","state":{"nums":[0,2,3,0,-2],"current":2,"labels":{"nums":"diff"}}},{"id":"mark-third","state":{"nums":[-2,2,3,2,-2],"labels":{"nums":"diff"}}},{"id":"sweep-mid","state":{"rows":[{"label":"diff","values":[-2,2,3,2,-2],"changed":[3]},{"label":"result","values":[-2,0,3,5,"—"],"changed":[3]}],"i":3}},{"id":"sweep-done","state":{"rows":[{"label":"diff","values":[-2,2,3,2,-2]},{"label":"result","values":[-2,0,3,5,3],"changed":[3,4]}],"i":4}}]},"beats":[{"id":"mark-first","title":"Which two slots does update [1,3,2] mark?","summary":"diff is all zeros. Update [1,3,2] turns +2 on at start and off after end.","prompt":"The first update covers indices 1 through 3 with +2.","options":[{"id":"one-and-four","label":"+2 at index 1, -2 at index 4","rationale":"Start is 1 and end + 1 is 4. The increment switches on at 1 and releases at 4, so it covers indices 1, 2, 3.","isCorrect":true},{"id":"one-and-three","label":"+2 at index 1, -2 at index 3","rationale":"Cancel at index 3 would drop the +2 before index 3 is covered. The release belongs at end + 1 = 4.","isCorrect":false},{"id":"all-three","label":"+2 at indices 1, 2, and 3","rationale":"Writing every covered index is the brute force. The diff array marks only the two edges.","isCorrect":false}],"answer":"diff becomes [0,2,0,0,-2]: +2 at start, -2 at end + 1."},{"id":"mark-second","title":"Update [2,4,3] ends at the last index. What about its -inc?","summary":"diff is [0,2,0,0,-2]. Update [2,4,3] should add 3 from index 2 through 4.","prompt":"end is 4, the final index of a length-5 array, so end + 1 is 5.","options":[{"id":"skip-cancel","label":"Add +3 at index 2 and skip the cancel, since index 5 is off the array","rationale":"end + 1 = 5 is past the last slot, so there is nothing left to switch the increment off. The +3 simply runs to the end. diff becomes [0,2,3,0,-2].","isCorrect":true},{"id":"cancel-at-four","label":"Add +3 at index 2 and -3 at index 4","rationale":"That would release the +3 before index 4 is covered, but the range includes index 4. The cancel only exists when end + 1 is inside the array.","isCorrect":false},{"id":"wrap-around","label":"Add +3 at index 2 and -3 at index 0","rationale":"There is no wraparound. When end + 1 falls off the array, the closing mark is simply skipped.","isCorrect":false}],"answer":"diff becomes [0,2,3,0,-2]: only the +3 at index 2 lands, because end + 1 is out of bounds."},{"id":"mark-third","title":"After update [0,2,-2], what is the full diff array?","summary":"diff is [0,2,3,0,-2]. Update [0,2,-2] subtracts 2 from index 0 through 2.","prompt":"A negative inc follows the same rule: -2 at start, +2 at end + 1.","options":[{"id":"final-diff","label":"[-2,2,3,2,-2]","rationale":"-2 lands at index 0 and the canceling +2 at index 3 (end + 1), added onto the 0 already there. Negative increments use the identical two-edge rule.","isCorrect":true},{"id":"no-cancel","label":"[-2,2,3,0,-2]","rationale":"The closing mark is missing. end is 2, so the +2 that cancels the -2 must land at index 3.","isCorrect":false},{"id":"subtract-both","label":"[-2,2,3,-2,-2]","rationale":"The closing mark is the opposite sign of inc. To cancel a -2 increment you add +2, not another -2.","isCorrect":false}],"answer":"diff is [-2,2,3,2,-2]. Every range left exactly two marks."},{"id":"sweep-mid","title":"Sweeping to index 3, what running total is written?","summary":"The sweep adds diff into a carried total left to right. The totals so far are -2 at index 0, 0 at index 1, and 3 at index 2.","prompt":"diff[3] is 2. Decide whether result[3] is that mark or the carried total after it absorbs the mark.","options":[{"id":"five","label":"5","rationale":"The total entering index 3 is 3, and 3 + diff[3] = 3 + 2 = 5. The carried total is the final value.","isCorrect":true},{"id":"just-diff","label":"2, writing diff[3] alone","rationale":"diff[3] is 2, and that is the edge mark. Here the running total (5) and the raw mark (2) clearly differ, so writing the mark would lose every increment opened before index 3.","isCorrect":false},{"id":"reset","label":"2, because the total resets at each index","rationale":"The total carries across indices; it never resets. Resetting would discard the +3 of running total already accumulated by index 2.","isCorrect":false}],"answer":"result[3] = 5. The running total carries the 3 from index 2 forward and adds diff[3] = 2 on top, so the value differs from the raw mark."},{"id":"sweep-done","title":"What array does the finished sweep return?","summary":"The total stands at 5 after index 3. The last step adds diff[4] = -2 to reach 3.","prompt":"The sweep carries the total through the final index.","options":[{"id":"final","label":"[-2,0,3,5,3]","rationale":"The carried totals are -2, 0, 3, 5, 3, matching the brute force exactly. Two marks per range plus one sweep reproduced every covered index.","isCorrect":true},{"id":"raw-diff","label":"[-2,2,3,2,-2], the diff array itself","rationale":"That is the marks before the sweep. The returned array uses the running totals.","isCorrect":false},{"id":"off-by","label":"[-2,0,3,3,1]","rationale":"That drops diff[3] = 2 from the carry. The total at index 3 is 3 + 2 = 5, and index 4 is 5 + (-2) = 3.","isCorrect":false}],"answer":"result = [-2,0,3,5,3]. The sweep over two marks per range matches the per-index brute force."}]},{"id":"off-by-one-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Does a boundary slot get assigned or added to?","summary":"Writing the marks with = instead of += reads cleanly, until two ranges touch the same slot. Run it on length = 5, updates [[0,2,3],[3,4,1]], whose answer is [3,3,3,1,1], and watch one mark erase another.","workspacePanel":"trace","pitfall":"The code below assigns the marks with = instead of accumulating with += and -=.","whyItMatters":"Use += and -= on the boundary slots. A diff array combines updates by adding their marks together, so when one range's closing slot is another range's opening slot, an assignment overwrites the earlier mark instead of stacking on it.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"diff = [0] * length\nfor start, end, inc in updates:\n    diff[start] = inc\n    if end + 1 < length:\n        diff[end + 1] = -inc\nrunning = 0\nfor i in range(length):\n    running += diff[i]\n    diff[i] = running\nreturn diff","steps":[{"id":"first-marks","title":"First range marks both edges","codeLine":5,"summary":"Update [0,2,3] writes +3 at index 0 and its cancel -3 at index 3 (end + 1). diff becomes [3,0,0,-3,0].","state":{"nums":[3,0,0,-3,0],"current":3,"labels":{"nums":"diff"}}},{"id":"overwrite","title":"The second start clobbers the first cancel","codeLine":3,"summary":"Update [3,4,1] assigns +1 at index 3, overwriting the -3 already there instead of adding to it. diff becomes [3,0,0,1,0] when it should be [3,0,0,-2,0].","state":{"nums":[3,0,0,1,0],"current":3,"labels":{"nums":"diff"}}},{"id":"wrong-result","title":"The first range never switches off","codeLine":9,"summary":"The sweep returns [3,3,3,4,4], but the answer is [3,3,3,1,1]. The lost -3 means the first range's +3 keeps running past index 2, so indices 3 and 4 read 4 instead of 1.","state":{"rows":[{"label":"diff","values":[3,0,0,1,0]},{"label":"result","values":[3,3,3,4,4],"changed":[3,4]}],"i":4}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const diff = Array(length).fill(0);\nfor (const [start, end, inc] of updates) {\n    diff[start] = inc;\n    if ((end + 1) < length) {\n        diff[(end + 1)] = -inc;\n    }\n}\nlet running = 0;\nfor (let i = 0; i < length; i++) {\n    running += diff[i];\n    diff[i] = running;\n}\nreturn diff;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":13},"statementBundles":{"5":{"startLine":5,"endLine":7},"9":{"startLine":11,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const diff = Array(length).fill(0);\nfor (const [start, end, inc] of updates) {\n    diff[start] = inc;\n    if ((end + 1) < length) {\n        diff[(end + 1)] = -inc;\n    }\n}\nlet running = 0;\nfor (let i = 0; i < length; i++) {\n    running += diff[i];\n    diff[i] = running;\n}\nreturn diff;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":13},"statementBundles":{"5":{"startLine":5,"endLine":7},"9":{"startLine":11,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> diff = new ArrayList<>();\nfor (int index = 0; index < length; index++) {\n    diff.add(0);\n}\nfor (List<Integer> update : updates) {\n    int start = update.get(0);\n    int end = update.get(1);\n    int inc = update.get(2);\n    diff.set(start, inc);\n    if ((end + 1) < length) {\n        diff.set((end + 1), -inc);\n    }\n}\nint running = 0;\nfor (int i = 0; i < length; i++) {\n    running += diff.get(i);\n    diff.set(i, running);\n}\nreturn diff;","lineMap":{"1":1,"2":5,"3":9,"4":10,"5":11,"6":14,"7":15,"8":16,"9":17,"10":19},"statementBundles":{"1":{"startLine":1,"endLine":4},"2":{"startLine":5,"endLine":8},"5":{"startLine":11,"endLine":13},"9":{"startLine":17,"endLine":18}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> diff = Enumerable.Repeat<int>(0, length).ToList();\nforeach (var item in updates) {\n    int start = item[0];\n    int end = item[1];\n    int inc = item[2];\n    diff[start] = inc;\n    if (end + 1 < length) {\n        diff[end + 1] = -inc;\n    }\n}\nint running = 0;\nfor (int i = 0; i < length; i++) {\n    running += diff[i];\n    diff[i] = running;\n}\nreturn diff;","lineMap":{"1":1,"2":2,"3":6,"4":7,"5":8,"6":11,"7":12,"8":13,"9":14,"10":16},"statementBundles":{"2":{"startLine":2,"endLine":5},"5":{"startLine":8,"endLine":10},"9":{"startLine":14,"endLine":15}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> diff = vector<int>(length, 0);\nfor (vector<int> item : updates) {\n    int start = item[0];\n    int end = item[1];\n    int inc = item[2];\n    diff[start] = inc;\n    if ((end + 1) < length) {\n        diff[(end + 1)] = -inc;\n    }\n}\nint running = 0;\nfor (int i = 0; i < length; i++) {\n    running += diff[i];\n    diff[i] = running;\n}\nreturn diff;","lineMap":{"1":1,"2":2,"3":6,"4":7,"5":8,"6":11,"7":12,"8":13,"9":14,"10":16},"statementBundles":{"2":{"startLine":2,"endLine":5},"5":{"startLine":8,"endLine":10},"9":{"startLine":14,"endLine":15}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Two inputs that test the marks","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"nums":[0,0,0,0,0],"labels":{"nums":"diff"}}}]},"body":["The two-marks-and-sweep idea rests on the closing mark landing in bounds and the diff array starting from zeros. Push on both.","First a range that ends at the very last index; then an empty update list."]},{"id":"edge-last-index","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What happens when a range ends at the last index?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-last-state","state":{"nums":[1,0,0],"current":0,"labels":{"nums":"diff"}}}]},"summary":"length = 3, updates = [[0,2,1]]. The range covers the whole array, so end + 1 is 3.","options":[{"id":"skip-the-mark","label":"Skip the closing -inc, since end + 1 is past the array","rationale":"The +1 at index 0 simply runs to the end with nothing to cancel it. The bounds check end + 1 < length is exactly what guards this. The sweep gives [1,1,1].","isCorrect":true},{"id":"crash","label":"Write -inc at index 3 and grow the array","rationale":"Index 3 does not exist in a length-3 array; writing there is an out-of-bounds error. When end + 1 is off the array, the closing mark is simply omitted.","isCorrect":false},{"id":"wrong-cancel","label":"Write the -inc at index 2 instead","rationale":"That is the off-by-one pitfall again: it would cancel the +1 before index 2 is covered, leaving [1,1,0].","isCorrect":false}],"answer":"Only write the closing -inc when end + 1 < length. A full-array range leaves a single opening mark."},{"id":"edge-empty","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does an empty update list return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-empty-state","state":{"nums":[0,0,0,0],"labels":{"nums":"diff"}}}]},"summary":"length = 4, updates = []. No ranges mark anything.","options":[{"id":"all-zeros","label":"[0,0,0,0], straight from the initialized diff array","rationale":"With no updates, diff stays all zeros. The sweep carries a running total of 0 across every index, so the zeros pass through untouched.","isCorrect":true},{"id":"empty-array","label":"An empty array, since there were no updates","rationale":"The array still has length 4. No updates means every value stays 0, not that the array disappears.","isCorrect":false},{"id":"needs-guard","label":"It needs a special case for the empty list","rationale":"No branch is needed. The update loop simply runs zero times and the sweep over all-zeros returns zeros.","isCorrect":false}],"answer":"The diff array of zeros sweeps to [0,0,0,0] with no special case. Initializing to zeros handles the empty input for free."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The end + 1 cancel and its bounds check carry the correctness.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[0,0,0,0,0],"labels":{"nums":"diff"}}}]},"body":["Start a diff array of zeros. For each range, add inc at start and subtract inc just past end when that index exists. Then sweep once, carrying a running total, and write it back at each index as the final value."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the diff-array sweep","eyebrow":"Build the solution","summary":"Initialize the diff array, apply guarded boundary deltas, sweep the running totals, write each value, and return the array.","workspacePanel":"code","checkpoints":[{"id":"init-diff","title":"Initialize the difference array","description":"Create a zero-filled array that will store boundary changes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"initializes_boundary_state","scope":"init-boundary","readMode":"sweep-line-value-query-v1"}]},"commonMistakes":["Starting from the input updates instead of an output-sized array","Creating an array with the wrong length"],"hint":"The boundary state should have one slot for each output index.","semanticSpec":{"intent":"Initialize dense boundary state for a diff-array sweep.","doneWhen":"A zero-filled boundary array exists before applying updates.","shouldFailWhen":"This step should fail if no boundary state is initialized.","roles":["difference array"],"mustProve":["The solution initializes sweep-line boundary state."],"mustNotAccept":["Updating the final output in every range without boundary state."]}},{"id":"apply-deltas","title":"Apply paired boundary deltas","description":"For each update, add at `start` and subtract at `end + 1` when that boundary is inside the array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"applies_boundary_deltas","scope":"apply-deltas","readMode":"sweep-line-value-query-v1"}]},"commonMistakes":["Forgetting the negative boundary","Subtracting at `end` instead of `end + 1`","Writing past the end of the array"],"hint":"The positive boundary starts the increment; the negative boundary stops it after `end`.","semanticSpec":{"intent":"Record paired positive and negative boundary deltas.","doneWhen":"The update loop writes both entering and leaving deltas to the boundary state.","shouldFailWhen":"This step should fail if only one side of the range is marked.","roles":["start boundary","end boundary","difference array"],"mustProve":["The solution applies paired boundary deltas."],"mustNotAccept":["Only adding at the start boundary."]}},{"id":"sweep-values","title":"Sweep the boundary array","description":"Scan the difference array in order while carrying the active running total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"performs_ordered_sweep","scope":"sweep-values","readMode":"sweep-line-value-query-v1"}]},"commonMistakes":["Returning the raw difference array","Resetting the running total on every index"],"hint":"Each index's final value is the running sum of all boundary changes up to that index.","semanticSpec":{"intent":"Perform an ordered accumulation sweep over boundary state.","doneWhen":"The code scans the boundary array and updates a carried running value.","shouldFailWhen":"This step should fail if no ordered sweep happens after updates.","roles":["running total","difference array"],"mustProve":["The solution performs an ordered sweep."],"mustNotAccept":["Returning boundary deltas without accumulating them."]}},{"id":"write-output","title":"Write accumulated values","description":"Store the running total back into the dense result position during the sweep.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"writes_dense_sweep_output","scope":"write-output","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Computing the running total but never saving it","Appending values in a different order than the array indices"],"hint":"After adding `diff[i]` into the running total, write that total as the final value at `i`.","semanticSpec":{"intent":"Materialize the dense output from the running sweep value.","doneWhen":"The sweep writes the accumulated running value into the dense state.","shouldFailWhen":"This step should fail if the sweep total is not written to output.","roles":["running total","output array"],"mustProve":["The solution writes the dense sweep output."],"mustNotAccept":["Only tracking a scalar total without storing final values."]}},{"id":"return-result","title":"Return the final array","description":"Return the dense array after all boundary deltas have been swept.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sweep-line","fact":"returns_sweep_result","scope":"return-answer","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Returning the updates list","Returning a fresh empty array","Returning before the sweep"],"hint":"The diff array has become the final array after the sweep, so return it.","semanticSpec":{"intent":"Return the completed dense sweep result.","doneWhen":"The terminal return uses the swept output state.","shouldFailWhen":"This step should fail if the return ignores the swept state.","roles":["output array"],"mustProve":["The solution returns the sweep result."],"mustNotAccept":["Returning an unrelated array."]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["A range update uses two edge marks. Record +inc at start and -inc after end, and a single running total reconstructs every covered index.","The whole correctness load sits in two small places: the cancel at end + 1 (not end), and the bounds check that skips it when the range reaches the array's edge."],"takeaways":[{"title":"Mark the range edges","body":"Inside a range the change is constant, so only its two boundaries differ from their neighbors. Two marks per update replace a per-index walk."},{"title":"The sweep rebuilds the span","body":"A left-to-right running total over diff turns the edge marks back into values: each index is the sum of every increment opened and not yet closed before it."},{"title":"Cancel just past end","body":"The range covers end inclusively, so the -inc belongs at end + 1, and only when that index is still inside the array. This drops the cost from O(length * updates) to O(length + updates)."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
