{"id":"range-sum-query-immutable","title":"Range Sum Query - Immutable","difficulty":"easy","patterns":["prefix-sum"],"primaryConcept":"array-prefix-sum-basics","concepts":["array-prefix-sum-basics"],"problemForm":"core","companies":["Amazon","Google","Microsoft"],"category":"arrays-strings","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","secondaryParam":"arguments","sizeMetric":"op-count","opVocabulary":[{"name":"NumArray","arity":1,"argTypes":["int[]"],"weight":1},{"name":"sumRange","arity":2,"argTypes":["int","int"],"weight":5}]},"description":"Design a `NumArray` class that stores an immutable integer array and answers `sumRange(left, right)` queries. Each query should return the sum of `nums[left]` through `nums[right]`, inclusive.","examples":[{"input":"operations = [\"NumArray\",\"sumRange\",\"sumRange\",\"sumRange\"]\narguments = [[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]","output":"[null,1,-1,-3]","explanation":"The sums are -2+0+3 = 1, 3-5+2-1 = -1, and the full array sum is -3."},{"input":"operations = [\"NumArray\",\"sumRange\",\"sumRange\"]\narguments = [[[1,2,3,4]],[1,3],[0,0]]","output":"[null,9,1]","explanation":"The prefix table lets each range be answered by subtracting two prefix values."}],"constraints":[{"id":"1-len-nums-10-4","text":"1 <= len(nums) <= 10^4"},{"id":"10-5-nums-i-10-5","text":"-10^5 <= nums[i] <= 10^5"},{"id":"0-left-right-len-nums","text":"0 <= left <= right < len(nums)"},{"id":"at-most-10-4-calls-will-be-made-to-sumrange","text":"At most 10^4 calls will be made to sumRange"},{"id":"the-array-does-not-change-after-numarray-is-constructed","text":"The array does not change after NumArray is constructed"}],"starterCode":"class NumArray:\n    def __init__(self, nums: list[int]):\n        # Your code here\n        pass\n\n    def sumRange(self, left: int, right: int) -> int:\n        # Your code here\n        pass","functionName":"NumArray","testCases":[{"id":"1","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]},"expected":[null,1,-1,-3],"description":"Canonical prefix-sum range query stream."},{"id":"2","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[1,2,3,4]],[1,3],[0,0],[0,3]]},"expected":[null,9,1,10],"description":"Queries over suffix, single element, and full array."},{"id":"3","input":{"operations":["NumArray","sumRange"],"arguments":[[[5]],[0,0]]},"expected":[null,5],"description":"Single-element array."},{"id":"h1","input":{"operations":["NumArray","sumRange","sumRange"],"arguments":[[[0,0,0]],[0,2],[1,1]]},"expected":[null,0,0],"description":"All zeros."},{"id":"h2","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[100,-50,25,-75,10]],[0,1],[1,3],[2,4]]},"expected":[null,50,-100,-40],"description":"Mixed positive and negative values."},{"id":"h3","input":{"operations":["NumArray","sumRange","sumRange"],"arguments":[[[-4,-3,-2,-1]],[0,3],[2,2]]},"expected":[null,-10,-2],"description":"All negative values."},{"id":"h4","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[1,-1,2,-2,3]],[0,4],[1,3],[2,2]]},"expected":[null,3,-1,2]},{"id":"h5","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[7,7,7]],[0,1],[1,2],[0,2]]},"expected":[null,14,14,21]},{"id":"h6","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[-5,5,-5,5]],[0,1],[1,2],[2,3]]},"expected":[null,0,0,0]},{"id":"h7","input":{"operations":["NumArray","sumRange","sumRange","sumRange"],"arguments":[[[2,-2,2,-2,2]],[0,4],[1,3],[2,2]]},"expected":[null,2,-2,2]}],"hints":[{"level":1,"content":"Repeated range-sum queries should not rescan the same array segment every time.","revealPattern":false},{"level":2,"content":"Build a prefix array where `prefix[i]` stores the sum of the first `i` numbers.","revealPattern":true},{"level":3,"content":"With a leading zero, `sumRange(left, right)` becomes `prefix[right + 1] - prefix[left]`.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-each-query","name":"Scan each query range","summary":"For every sumRange call, loop from left to right and add the values.","decisionReason":"A long query like sumRange(0, n - 1) rereads every value, and repeated calls reread the same prefixes again. The immutable array lets that work move into one build step instead.","complexity":{"time":"O(n) per query","space":"O(1)"},"tradeoffs":["Runs in O(n) per query time and uses O(1) space."],"isOptimal":false},{"id":"prefix-array","name":"Build a prefix array","summary":"Precompute cumulative sums once, then answer each query with two array reads.","decisionReason":"prefix[i] stores the sum before index i, so sumRange(left, right) is just prefix[right + 1] - prefix[left]. Because nums never changes, that one O(n) table answers every later query with two reads.","complexity":{"time":"O(n) build, O(1) per query","space":"O(n)"},"tradeoffs":["Runs in O(n) build, O(1) per query time and uses O(n) space."],"isOptimal":true},{"id":"segment-tree","name":"Segment tree","summary":"A segment tree supports updates, but this array is immutable so it is more machinery than needed.","decisionReason":"A segment tree keeps update machinery for changing ranges, but NumArray never mutates nums. Its log n query path is extra work compared with the two prefix entries an immutable array needs.","complexity":{"time":"O(n) build, O(log n) per query","space":"O(n)"},"tradeoffs":["Runs in O(n) build, O(log n) per query time and uses O(n) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"compute-prefix","title":"Create a leading-zero prefix table","description":"Allocate prefix storage with one extra leading zero so query bounds can be converted cleanly.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"range-query","fact":"initializes_zero_seeded_prefix_state","scope":"compute-prefix","readMode":"range-query-value-query-v1"}]},"commonMistakes":["Forgetting the leading zero","Creating a prefix table with the same length as nums"],"hint":"Use one extra slot: `prefix[0]` represents the empty prefix before index 0.","semanticSpec":{"intent":"Initialize a zero-seeded prefix state for range queries.","doneWhen":"The constructor creates prefix storage seeded with zero before the build loop.","shouldFailWhen":"This step should fail if there is no reusable prefix state or no zero seed.","roles":["prefix state","zero seed"],"mustProve":["A persistent prefix state is initialized with a zero seed."],"mustNotAccept":["Only storing the original input without prefix state."]}},{"id":"build-prefix","title":"Build cumulative sums","description":"Fill each later prefix cell from the previous prefix total plus the next input value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"range-query","fact":"builds_prefix_accumulator_values","scope":"build-prefix","readMode":"range-query-value-query-v1"}]},"commonMistakes":["Copying values instead of accumulating them","Using the wrong offset when writing prefix[i + 1]"],"hint":"Each prefix cell should extend the previous prefix cell by exactly one input value.","semanticSpec":{"intent":"Build prefix accumulator values from the immutable input array.","doneWhen":"The constructor writes cumulative prefix values across the input.","shouldFailWhen":"This step should fail if prefix values are not accumulated.","roles":["input array","prefix state","cumulative write"],"mustProve":["The prefix state is filled by an accumulator build."],"mustNotAccept":["A table of raw copied input values."]}},{"id":"query-range","title":"Answer with two prefix reads","description":"Return the inclusive range sum by subtracting the prefix before left from the prefix after right.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"range-query","fact":"returns_prefix_range_difference","scope":"query-range","readMode":"range-query-value-query-v1"}]},"commonMistakes":["Using prefix[right] instead of prefix[right + 1]","Subtracting the wrong side of the range","Looping through the query range despite having prefix sums"],"hint":"The inclusive right boundary maps to `right + 1` in the leading-zero prefix table.","semanticSpec":{"intent":"Answer each query with a prefix-difference expression.","doneWhen":"sumRange returns `prefix[right + 1] - prefix[left]` or an equivalent prefix-bound difference.","shouldFailWhen":"This step should fail if the right boundary is not offset or if the query scans the raw range.","roles":["left bound","right bound","prefix difference"],"mustProve":["The query returns a range difference over the prefix state."],"mustNotAccept":["Returning a single prefix value.","Using `right` as an exclusive bound by accident."]}}],"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Answer the same array, asked over and over","workspacePanel":"problem","body":["Build a NumArray over a fixed list of integers, then answer many sumRange(left, right) calls. Each call returns the sum of nums[left] through nums[right], inclusive. The array never changes after it is built.","The obvious way is to add up the requested stretch on every call. Watch it work, then watch what it repeats."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Add up the stretch each call","summary":"It returns the right answer. Watch how much of the array each call re-adds.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def sumRange(nums: list[int], left: int, right: int) -> int:\n    total = 0\n    k = left\n    while k <= right:\n        total += nums[k]\n        k += 1\n    return total","steps":[{"id":"first-query","title":"sumRange(2, 5) walks four cells","codeLine":5,"summary":"left = 2, right = 5: the loop reads nums[2], nums[3], nums[4], nums[5] and accumulates 3, -2, 0, -1. total ends at -1.","state":{"nums":[-2,0,3,-5,2,-1],"left":2,"right":5,"current":5,"total":-1,"labels":{"left":"left","right":"right"}}},{"id":"second-query","title":"sumRange(0, 5) walks all six","codeLine":5,"summary":"A second call with left = 0, right = 5 runs the same loop again over the whole array, re-reading nums[2..5] the first call just summed.","state":{"nums":[-2,0,3,-5,2,-1],"left":0,"right":5,"current":5,"total":-3,"labels":{"left":"left","right":"right"}}},{"id":"repeated-work","title":"Every call starts its sum from zero","codeLine":2,"summary":"Each call enters with total = 0 and walks its own range from scratch, so overlapping ranges re-add the same cells across calls.","state":{"nums":[-2,0,3,-5,2,-1],"left":1,"right":4,"current":1,"total":0,"labels":{"left":"left","right":"right"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let total = 0;\nlet k = left;\nwhile (k <= right) {\n    total += nums[k];\n    k++;\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7},"statementBundles":{"6":{"startLine":5,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let total = 0;\nlet k = left;\nwhile (k <= right) {\n    total += nums[k];\n    k++;\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7},"statementBundles":{"6":{"startLine":5,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int total = 0;\nint k = left;\nwhile (k <= right) {\n    total += nums.get(k);\n    k++;\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7},"statementBundles":{"6":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int total = 0;\nint k = left;\nwhile (k <= right) {\n    total += nums[k];\n    k++;\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7},"statementBundles":{"6":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int total = 0;\nint k = left;\nwhile (k <= right) {\n    total += nums[k];\n    k++;\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7},"statementBundles":{"6":{"startLine":5,"endLine":6}}}}},"body":["Each call sets total to 0 and walks the requested range left to right, adding cells. Nothing carries over between calls."]},{"id":"rescan-cost","chapter":"The problem","kind":"case-probe","eyebrow":"Name the cost","title":"What does one call cost when the range is the whole array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rescan-state","state":{"nums":[-2,0,3,-5,2,-1],"left":0,"right":5,"current":5,"labels":{"left":"left","right":"right"}}}]},"summary":"sumRange(0, 5) touched all six cells; the constraints allow up to 10^4 calls on an array of up to 10^4 elements.","options":[{"id":"linear-each","label":"Up to n cells per call, so many wide calls cost about (calls x n) work","rationale":"A call spanning the whole array reads every element. With many such calls the same cells get re-added thousands of times over.","isCorrect":true},{"id":"constant","label":"Constant, because it is just one loop","rationale":"One loop, but its length is the range width, which can be the whole array. Cost grows with how wide the range is.","isCorrect":false},{"id":"depends-values","label":"It depends on the values in the range","rationale":"The values change the total while the loop still runs once per cell.","isCorrect":false}],"answer":"Each wide call is O(n), and the same interior cells are re-summed across overlapping calls. The repeated work is what a precomputation can erase."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which stored quantity answers any range in one step?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pattern-quiz-state","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"precompute?","values":["?","?","?","?","?","?"]}]}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which stored quantity answers any range in one step?","signalPrompt":"The array is fixed. What could you compute once so that sumRange(left, right) becomes arithmetic on two stored numbers instead of a loop?","options":[{"id":"prefix-totals","label":"The running total from the start up to each position","signal":"sum[left..right] = total[0..right] - total[0..left-1].","rationale":"Keep the cumulative sum at every position and any range is the difference of two of them. One subtraction replaces the whole loop.","isCorrect":true},{"id":"two-pointers","label":"Two pointers that slide across the range","signal":"Two pointers handle a moving window.","rationale":"Queries jump to arbitrary left and right. There is no single span to advance by one each time.","isCorrect":false},{"id":"sorted-copy","label":"A sorted copy of the array","signal":"Sorted data unlocks binary search.","rationale":"Sorting destroys the positions the query is defined on. sumRange asks about original indices, which sorting scrambles.","isCorrect":false},{"id":"max-heap","label":"A heap of the largest values","signal":"A heap surfaces extremes fast.","rationale":"A heap tracks the biggest items. sumRange asks for the sum over an index range.","isCorrect":false}],"missFeedback":"The array never changes, so precompute. A range sum is the difference of two from-the-start totals."}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which precomputation fits a fixed array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-selection-state","state":{"rows":[{"label":"nums (fixed)","values":[-2,0,3,-5,2,-1]},{"label":"prefix (pending)","values":["0","—","—","—","—","—","—"]}]}}]}},{"id":"prefix-state","chapter":"The idea","kind":"case-probe","eyebrow":"Set up the state","title":"Which stored total lets a later range come from two cells?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"prefix-state-state","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"stored totals","values":["?","?","?","?","?","?"]}],"i":3}}]},"summary":"A second row of stored totals is still blank.","options":[{"id":"cumulative","label":"The running total of every nums value up to that position","rationale":"If each cell holds the sum from the start, two cells differ by exactly the values between them. Subtracting them leaves one range, which is the whole point.","isCorrect":true},{"id":"copy","label":"Just a copy of nums[i]","rationale":"Copies give you back the original array and the same per-call loop. You still have to add the cells in the range, so nothing is saved.","isCorrect":false},{"id":"running-max","label":"The largest nums value seen so far up to that position","rationale":"A running maximum answers questions about extremes, not sums. Two maxima do not subtract into a range sum.","isCorrect":false}],"answer":"Store the cumulative total: each cell holds the sum of the elements before it. Call this row prefix, where prefix[i] is the sum of the first i elements. Subtracting two prefix cells leaves exactly the interval between them."},{"id":"boundary-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"What total does a range that starts at index 0 subtract?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"boundary-state","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[-2,-2,1,-4,-2,-3]}],"i":0}}]},"summary":"A range like sumRange(0, right) keeps everything from index 0 onward, so it must subtract the total of everything before index 0. If prefix only stores totals at positions 0 through 5, what number represents \"before index 0\"?","options":[{"id":"left-edge","label":"The total of no elements, which is 0, so prefix should carry a leading 0","rationale":"Before index 0 there is nothing, and the sum of nothing is 0. Giving prefix a leading zero stores that empty-front total, so a range starting at index 0 has a real cell to subtract.","isCorrect":true},{"id":"off-by-default","label":"prefix[0] itself, the total through index 0","rationale":"That already includes nums[0], so subtracting it would drop the first element from any range starting at index 0. What we need is the total strictly before index 0.","isCorrect":false},{"id":"special-case","label":"Nothing; left = 0 needs its own special branch","rationale":"A branch works but is avoidable. Storing the empty-front total once removes the need to special-case the left edge at all.","isCorrect":false}],"answer":"It subtracts the empty-front total, which is 0. So prefix carries a leading zero before nums[0], giving it one more cell than nums (length 7 for a 6-element array). Every range that starts at index 0 then has a stored total to subtract, with no special case."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Build once, then subtract","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0]}],"i":0}}]},"body":["Now watch the prefix row fill in, one cell at a time, from the same nums = [-2, 0, 3, -5, 2, -1].","The trace checks one thing at each step: do the stored totals line up so that an inclusive query like sumRange(2, 5) falls out of two cells? Predict each cell before it lands."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the build","title":"Trace the prefix table and one query","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fold-first","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2],"changed":[1]}],"i":1}},{"id":"fold-third","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2,-2,1],"changed":[3]}],"i":3}},{"id":"answer-query","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3],"changed":[2,6]}],"i":6}}]},"beats":[{"id":"fold-first","title":"What does prefix[1] become?","summary":"The build is about to write the first cell after the leading zero.","prompt":"prefix so far is [0], and the next value to fold in is nums[0].","options":[{"id":"minus-two","label":"The previous total plus nums[0]","rationale":"prefix[1] = prefix[0] + nums[0] = 0 + (-2) = -2. Each cell extends the one before it by exactly one value.","isCorrect":true},{"id":"zero","label":"Copy the previous total unchanged","rationale":"Copying ignores nums[0]. The build must add the next value, not repeat the running total.","isCorrect":false},{"id":"raw","label":"Whatever nums[1] holds","rationale":"prefix[1] is a running total of the front. It folds in nums[0], the element just passed.","isCorrect":false}],"answer":"prefix[1] = prefix[0] + nums[0] = 0 + (-2) = -2. The fold rule is prefix[i + 1] = prefix[i] + nums[i]."},{"id":"fold-third","title":"After folding nums[2], what is prefix[3]?","summary":"prefix so far is [0, -2, -2].","prompt":"The next value to fold in is nums[2] = 3.","options":[{"id":"one","label":"The previous total plus nums[2]","rationale":"prefix[3] = prefix[2] + nums[2] = -2 + 3 = 1, the sum of the first three elements -2 + 0 + 3.","isCorrect":true},{"id":"three","label":"Just nums[2] on its own","rationale":"That drops the front sum. prefix[3] must include nums[0..2], not only the latest element.","isCorrect":false},{"id":"neg-five","label":"The previous total minus nums[2]","rationale":"The build accumulates by adding each value. Subtraction happens later when sumRange reads from prefix.","isCorrect":false}],"answer":"prefix[3] = prefix[2] + nums[2] = -2 + 3 = 1. Once filled, prefix = [0, -2, -2, 1, -4, -2, -3]."},{"id":"answer-query","title":"What does sumRange(2, 5) compute?","summary":"The table is full at [0, -2, -2, 1, -4, -2, -3].","prompt":"sumRange(2, 5) asks for nums[2..5].","options":[{"id":"diff","label":"The cell after right minus the cell at left","rationale":"prefix[6] - prefix[2] = -3 - (-2) = -1 strips off the front up to index 2 and keeps nums[2..5]. The inclusive right index maps to the cell one past it.","isCorrect":true},{"id":"no-offset","label":"The cell at right minus the cell at left","rationale":"prefix[5] - prefix[2] = -2 - (-2) = 0 drops nums[5]. The inclusive right boundary needs the cell one past right.","isCorrect":false},{"id":"loop","label":"Scan nums[2..5] again and add","rationale":"That is the brute force again. The whole point of the table is to replace the loop with one subtraction.","isCorrect":false}],"answer":"sumRange(2, 5) = prefix[6] - prefix[2] = -3 - (-2) = -1, with no loop. The inclusive right index 5 maps to prefix[6], the cell one past it."}]},{"id":"offbyone-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the query just use prefix[right]?","summary":"Writing prefix[right] - prefix[left] looks like the two boundary totals and reads cleanly. Run it on sumRange(2, 5) for prefix = [0, -2, -2, 1, -4, -2, -3] before trusting it.","workspacePanel":"trace","pitfall":"The query below subtracts prefix[left] from prefix[right] instead of prefix[right + 1].","whyItMatters":"Use prefix[right + 1] - prefix[left]. Because prefix[i] is the sum of the first i elements, the inclusive right index right corresponds to prefix[right + 1]; dropping the +1 silently excludes nums[right] from every answer.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class NumArray:\n    def __init__(self, nums: list[int]) -> None:\n        self.prefix: list[int] = [0] * (len(nums) + 1)\n        for i in range(len(nums)):\n            self.prefix[i + 1] = self.prefix[i] + nums[i]\n\n    def sumRange(self, left: int, right: int) -> int:\n        return self.prefix[right] - self.prefix[left]","steps":[{"id":"wrong-read","title":"The query reads prefix[right]","codeLine":8,"summary":"sumRange(2, 5): the code computes prefix[5] - prefix[2] = -2 - (-2) = 0. It read up to index 4, not index 5.","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3],"changed":[2,5]}],"i":5}},{"id":"missing-cell","title":"nums[5] never enters the sum","codeLine":8,"summary":"prefix[5] covers nums[0..4], so subtracting prefix[2] leaves nums[2..4] = 3 - 5 + 2 = 0. nums[5] = -1 is missing.","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1],"changed":[5]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3],"changed":[5]}],"i":5}},{"id":"wrong-answer","title":"Off by exactly the right endpoint","codeLine":8,"summary":"It returns 0; the true sum of nums[2..5] is -1. The error is always the dropped nums[right], so it hides whenever that cell happens to be 0.","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3],"changed":[6]}],"i":6}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class NumArray {\n    constructor(nums) {\n        this.prefix = Array((nums.length + 1)).fill(0);\n        for (let i = 0; i < nums.length; i++) {\n            this.prefix[(i + 1)] = (this.prefix[i] + nums[i]);\n        }\n    }\n\n    sumRange(left, right) {\n        return (this.prefix[right] - this.prefix[left]);\n    }\n}","lineMap":{"3":3,"4":4,"5":5,"8":10},"statementBundles":{"5":{"startLine":5,"endLine":9},"8":{"startLine":10,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class NumArray {\n    prefix: Array<number>;\n\n    constructor(nums: Array<number>) {\n        this.prefix = Array((nums.length + 1)).fill(0);\n        for (let i = 0; i < nums.length; i++) {\n            this.prefix[(i + 1)] = (this.prefix[i] + nums[i]);\n        }\n    }\n\n    sumRange(left: number, right: number): number {\n        return (this.prefix[right] - this.prefix[left]);\n    }\n}","lineMap":{"3":5,"4":6,"5":7,"8":12},"statementBundles":{"5":{"startLine":7,"endLine":11},"8":{"startLine":12,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class NumArray {\n    List<Integer> prefix;\n\n    public NumArray(List<Integer> nums) {\n        this.prefix = new ArrayList<Integer>();\n        for (int value = 0; value < (nums.size() + 1); value++) this.prefix.add(0);\n        for (int i = 0; i < nums.size(); i++) {\n            this.prefix.set((i + 1), (this.prefix.get(i) + nums.get(i)));\n        }\n    }\n\n    public int sumRange(int left, int right) {\n        return (this.prefix.get(right) - this.prefix.get(left));\n    }\n}","lineMap":{"3":5,"4":7,"5":8,"8":13},"statementBundles":{"3":{"startLine":5,"endLine":6},"5":{"startLine":8,"endLine":12},"8":{"startLine":13,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class NumArray\n{\n    public List<int> prefix;\n\n    public NumArray(List<int> nums)\n    {\n        this.prefix = Enumerable.Repeat<int>(0, nums.Count + 1).ToList();\n        for (int i = 0; i < nums.Count; i++) {\n            this.prefix[i + 1] = this.prefix[i] + nums[i];\n        }\n    }\n\n    public int SumRange(int left, int right)\n    {\n        return this.prefix[right] - this.prefix[left];\n        return 0;\n    }\n}","lineMap":{"3":7,"4":8,"5":9,"8":15},"statementBundles":{"5":{"startLine":9,"endLine":14},"8":{"startLine":15,"endLine":18}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct NumArray {\n    vector<int> prefix;\n\n    NumArray(vector<int> nums) {\n        this->prefix = vector<int>((nums.size() + 1), 0);\n        for (int i = 0; i < nums.size(); i++) {\n            this->prefix[(i + 1)] = (this->prefix[i] + nums[i]);\n        }\n    }\n\n    int sum_range(int left, int right) {\n        return (this->prefix[right] - this->prefix[left]);\n    }\n};","lineMap":{"3":5,"4":6,"5":7,"8":12},"statementBundles":{"5":{"startLine":7,"endLine":11},"8":{"startLine":12,"endLine":14}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Two ranges that test the offsets","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3]}]}}]},"body":["Two ranges deserve a check next: a single-element query where left equals right, and a query that covers the whole array from index 0.","Predict what each one does before stepping through it."]},{"id":"single-element-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does sumRange(2, 2) subtract?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1],"changed":[2]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3],"changed":[2,3]}],"i":2}}]},"summary":"left = right = 2, so the range is the single cell nums[2] = 3.","options":[{"id":"adjacent","label":"prefix[3] - prefix[2] = 1 - (-2) = 3, using two adjacent cells","rationale":"right + 1 = 3 and left = 2 are neighbors, and their difference is exactly nums[2]. The formula needs no special case for length-one ranges.","isCorrect":true},{"id":"zero-always","label":"0, from subtracting a cell from itself","rationale":"It would be prefix[2] - prefix[2] only if you forgot the +1. With prefix[right + 1] the two cells differ by one position.","isCorrect":false},{"id":"needs-branch","label":"It needs a special branch for left == right","rationale":"No branch is needed. The same prefix[right + 1] - prefix[left] handles a single cell as a difference of adjacent totals.","isCorrect":false}],"answer":"prefix[3] - prefix[2] = 3. A one-element range is just two adjacent prefix cells; the +1 offset makes it fall out automatically."},{"id":"full-array-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What makes sumRange(0, n - 1) need no special case?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"full-state","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0,-2,-2,1,-4,-2,-3],"changed":[0,6]}],"i":6}}]},"summary":"left = 0, right = 5 for this 6-element array, so the range is the entire array.","options":[{"id":"leading-zero","label":"The leading zero: prefix[6] - prefix[0] = -3 - 0 = -3","rationale":"prefix[0] = 0 is the empty-front total, so subtracting it keeps the whole array. Without that seed, the left edge would need its own branch.","isCorrect":true},{"id":"sum-prefix","label":"It returns prefix[6] directly, no subtraction","rationale":"It does equal prefix[6] here, but only because prefix[0] = 0. The formula is still a subtraction; the zero is what makes it land on prefix[6].","isCorrect":false},{"id":"special-full","label":"Full-array queries need a separate code path","rationale":"They do not. prefix[right + 1] - prefix[left] with left = 0 reuses the leading zero, so the whole-array case is the same single line.","isCorrect":false}],"answer":"prefix[6] - prefix[0] = -3. The leading zero is the left side of every from-the-front range, so left = 0 needs no special handling."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two moves: build the reusable totals once, then answer each query by difference.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"rows":[{"label":"nums","values":[-2,0,3,-5,2,-1]},{"label":"prefix","values":[0]}],"i":0}}]},"body":["In the constructor, build one reusable row of cumulative totals while reading nums once.","In sumRange, read the two boundary totals that surround the requested range and return their difference."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build prefix totals, then answer by difference","summary":"Seed prefix with 0, build cumulative totals, and answer queries with prefix[right + 1] - prefix[left].","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["A fixed array invites precomputation: pay O(n) once at build time so every later query is O(1).","The two correctness loads sit in small places: the leading zero (so left = 0 has a total to subtract) and the right + 1 offset (so the inclusive right cell is included)."],"takeaways":[{"title":"A range sum is a difference of totals","body":"sum[left..right] = prefix[right + 1] - prefix[left]. Storing cumulative totals once turns each query into one subtraction."},{"title":"The empty prefix is real","body":"prefix[0] = 0 is the sum of no elements, and the left side of every range that starts at index 0. It removes the left-boundary special case."},{"title":"The +1 tracks the inclusive end","body":"Because prefix[i] covers the first i elements, an inclusive right index maps to prefix[right + 1]. Dropping it silently omits nums[right]."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
