{"id":"product-of-array-except-self","title":"Product of Array Except Self","difficulty":"medium","patterns":["prefix-sum"],"primaryConcept":"array-prefix-sum-basics","concepts":["array-prefix-sum-basics"],"problemForm":"core","companies":[],"category":"arrays-strings","compareMode":"exact","description":"Given an integer array `nums`, return an array `answer` where `answer[i]` is the product of every element in `nums` except `nums[i]`.\n\nRequirements:\n- Do not use division.\n- Return the products in the same order as the input.\n- Your algorithm should run in O(n) time.\n- You may use the output array itself to store intermediate prefix/suffix products.","requiredComplexity":[{"metric":"time","bound":"O(n)","scope":"function","functions":["productExceptSelf"],"case":"worst","enforcement":"hard","reason":"The prompt requires O(n) time."}],"examples":[{"input":"nums = [1,2,3,4]","output":"[24,12,8,6]","explanation":"For each index, multiply all other numbers: 2*3*4=24, 1*3*4=12, and so on."},{"input":"nums = [5,3,0,2,1]","output":"[0,0,30,0,0]","explanation":"Only the position containing 0 has a non-zero product, because every other position includes that zero in its product."},{"input":"nums = [-1,1,0,-3,3]","output":"[0,0,9,0,0]","explanation":"The zero position gets the product of the non-zero values; every other position multiplies by zero."}],"constraints":[{"id":"2-len-nums-10-5","text":"2 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":2,"max":100000}},{"id":"30-nums-i-30","text":"-30 <= nums[i] <= 30","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-30,"max":30}},{"id":"the-product-of-any-prefix-or-suffix-fits-in-a-32-bit-signed-inte","text":"The product of any prefix or suffix fits in a 32-bit signed integer."},{"id":"do-not-use-division","text":"Do not use division."}],"starterCode":"class Solution:\n    def productExceptSelf(self, nums: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"productExceptSelf","testCases":[{"id":"1","input":{"nums":[1,2,3,4]},"expected":[24,12,8,6],"description":"Canonical positive values."},{"id":"2","input":{"nums":[5,3,0,2,1]},"expected":[0,0,30,0,0],"description":"Single zero should leave only the zero index non-zero."},{"id":"3","input":{"nums":[-1,1,0,-3,3]},"expected":[0,0,9,0,0],"description":"Negatives and a zero."},{"id":"4","input":{"nums":[0,4,0]},"expected":[0,0,0],"description":"Two zeros force every output to zero."},{"id":"5","input":{"nums":[-2,-3,4]},"expected":[-12,-8,6],"description":"Sign handling with no zero."},{"id":"h1","input":{"nums":[1,0]},"expected":[0,1],"description":"A two-element array with one zero."},{"id":"h2","input":{"nums":[-1,-2,-3,-4]},"expected":[-24,-12,-8,-6],"description":"An even number of negative values changes signs by excluded index."},{"id":"h3","input":{"nums":[2,3,4,5]},"expected":[60,40,30,24],"description":"A standard positive array with increasing products."},{"id":"h4","input":{"nums":[1,1,1,1]},"expected":[1,1,1,1],"description":"Uniform values keep every product the same."},{"id":"h5","input":{"nums":[5,-1,2]},"expected":[-2,10,-5],"description":"Negative values still follow the same prefix and suffix logic."},{"id":"topup-double-zero","input":{"nums":[2,-1,0,0,5]},"expected":[0,0,0,0,0],"description":"Two zero values force every product-except-self result to zero."},{"id":"topup-sign-bounds","input":{"nums":[30,-1,1,-1]},"expected":[1,-30,30,-30],"description":"Near-boundary value with paired negatives exercises sign handling without division."}],"hints":[{"level":1,"content":"For each index, think about the product to its left and the product to its right separately.","revealPattern":false},{"level":2,"content":"You can make one pass to store prefix products, then a second pass from the right to multiply in suffix products.","revealPattern":true},{"level":3,"content":"Initialize the output with prefix products. Keep a running `right` product while scanning backward and multiply it into each output cell before updating it.","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":"nested-products","name":"Compute each product separately","summary":"For every index, scan the whole array and multiply all other values.","decisionReason":"It rebuilds the product of the same neighbors for every slot, so the work grows with the square of the length.","complexity":{"time":"O(n^2)","space":"O(1) excluding output"},"tradeoffs":["Runs in O(n^2) time and uses O(1) excluding output space."],"isOptimal":false},{"id":"division","name":"Total product with division","summary":"Compute a total product and divide by nums[i]. This is disallowed and becomes tricky around zeros.","decisionReason":"The problem bans division, and it breaks on a zero: dividing the total product by a value of 0 is undefined.","complexity":{"time":"O(n)","space":"O(1) excluding output"},"tradeoffs":["Runs in O(n) time and uses O(1) excluding output space."],"isOptimal":false},{"id":"prefix-suffix","name":"Prefix pass + suffix pass","summary":"Store left-side products in the output, then sweep from the right and multiply in right-side products.","decisionReason":"Two linear sweeps. A forward pass writes each slot its left product, a backward pass folds in the right product, reusing the output for no extra array.","complexity":{"time":"O(n)","space":"O(1) excluding output"},"tradeoffs":["Runs in O(n) time and uses O(1) excluding output space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-output","title":"Initialize output for prefix products","description":"Create an output array filled with 1s so each position can accumulate products.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Starting with zeros, which would erase every product","Allocating the wrong length"],"hint":"Use 1 as the multiplication identity for every output cell.","semanticSpec":{"intent":"Initialize a same-length output sequence seeded with multiplication identity values.","doneWhen":"This step is done when a result list or array with one slot per input element exists before product passes begin.","shouldFailWhen":"This step should fail if the result is missing, scalar-only, or not sized from the input sequence.","roles":["input sequence","output sequence","multiplication identity"],"mustProve":["A result sequence is created before the product passes.","The result sequence is aligned to the input length."],"mustNotAccept":["Using a scalar total product only.","Returning the input array directly."],"equivalentVariants":["Use [1] * len(nums).","Use an equivalent same-length result initialized with neutral product values."],"proofSnippets":[{"id":"py-product-init-output","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    return answer"}]}},{"id":"left-pass","title":"Store products to the left","description":"Sweep left to right, write the running left product into answer[i], then multiply by nums[i].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"writes_forward_accumulator_to_indexed_result","scope":"left-pass","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Updating the running product before writing answer[i]","Including nums[i] in its own left product"],"hint":"At index i, answer[i] should represent values strictly before i.","semanticSpec":{"intent":"Run a left-to-right indexed pass that writes the product of values strictly to the left of each index before including the current value in the running product.","doneWhen":"This step is done when the code scans indices from the beginning, stores the current left product into the matching output slot, then updates the running product with nums[i].","shouldFailWhen":"This step should fail if the scan includes nums[i] in its own left product, updates the running product before writing the output slot, skips indices, or uses division instead of a directional product pass.","roles":["left-to-right index scan","running left product","current input value","output slot"],"mustProve":["The code performs an indexed traversal over nums from left to right or an equivalent prefix order.","At each index, the output slot receives the product accumulated before consuming nums[i].","The running left product is updated with the current value only after the slot is written."],"mustNotAccept":["Multiplying by nums[i] before writing answer[i].","Computing products by total division.","Writing a prefix product array that includes the current element for each index."],"equivalentVariants":["Use `for i in range(len(nums))` with `answer[i] = left` followed by `left *= nums[i]`.","Use an equivalent forward indexed loop that preserves the same before-current update order."],"proofSnippets":[{"id":"py-product-left-pass","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    left = 1\n    for i in range(len(nums)):\n        answer[i] = left\n        left *= nums[i]\n    return answer"}]}},{"id":"right-pass","title":"Multiply products from the right","description":"Sweep right to left with a running right product and multiply it into answer[i].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"combines_reverse_accumulator_into_indexed_result","scope":"right-pass","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Scanning from the wrong direction","Overwriting the prefix product instead of multiplying it"],"hint":"The second pass should combine, not replace, the left-side product.","semanticSpec":{"intent":"Run a right-to-left indexed pass that combines each stored left product with the product of values strictly to the right of that index.","doneWhen":"This step is done when the code scans indices from the end toward the beginning, multiplies the current output slot by the running right product, then updates the running product with nums[i].","shouldFailWhen":"This step should fail if the scan goes in the wrong direction, overwrites the stored left product instead of multiplying it, includes nums[i] in its own right product, or returns before finishing the suffix sweep.","roles":["right-to-left index scan","running right product","stored left product","combined output slot"],"mustProve":["The code performs a reverse indexed traversal over every input index.","At each index, the existing answer[i] value is multiplied by the product accumulated from indices to the right.","The running right product is updated with nums[i] only after answer[i] is combined."],"mustNotAccept":["Assigning answer[i] = right and discarding the left product.","Updating right before multiplying answer[i].","Scanning forward for the suffix pass without equivalent reversed semantics."],"equivalentVariants":["Use `for i in range(len(nums) - 1, -1, -1)` with `answer[i] *= right` followed by `right *= nums[i]`.","Use any equivalent reverse traversal that combines suffix products into the existing output array."],"neededLowerLayerFact":{"suggestedFamily":"array-scan","suggestedFact":"combines_reverse_accumulator_into_indexed_result","suggestedScope":"right-pass","owner":"Layer 5A structural facts first, then Layer 6 familyFact reader"},"proofSnippets":[{"id":"py-product-right-pass","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    left = 1\n    for i in range(len(nums)):\n        answer[i] = left\n        left *= nums[i]\n    right = 1\n    for i in range(len(nums) - 1, -1, -1):\n        answer[i] *= right\n        right *= nums[i]\n    return 0"}]}},{"id":"return-answer","title":"Return the completed output","description":"Return the output array after both directional products have been merged.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"combines_reverse_accumulator_into_indexed_result","scope":"right-pass","readMode":"array-scan-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}]},"commonMistakes":["Returning the running suffix variable","Returning before the backward pass finishes"],"hint":"The answer array is complete only after the suffix sweep reaches index 0.","semanticSpec":{"intent":"Return the completed output array after both directional product passes have contributed to every slot.","doneWhen":"This step is done when the function returns the output sequence that was initialized and updated by the left and right product passes.","shouldFailWhen":"This step should fail if the function returns a running scalar, returns too early before the reverse pass completes, returns the input array unchanged, or returns only one directional pass.","roles":["completed output array","left product contributions","right product contributions","terminal return"],"mustProve":["The returned value is the product result sequence.","The return occurs after both directional passes in the normal control-flow path."],"mustNotAccept":["Returning `left` or `right`.","Returning before the suffix pass.","Returning a prefix-only result."],"equivalentVariants":["Return `answer` after the reverse pass.","Return any same-length result array that has been populated by both directional product sweeps."],"proofSnippets":[{"id":"py-product-return-answer","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    left = 1\n    for i in range(len(nums)):\n        answer[i] = left\n        left *= nums[i]\n    right = 1\n    for i in range(len(nums) - 1, -1, -1):\n        answer[i] *= right\n        right *= nums[i]\n    return answer"}]}}],"version":2,"slides":[{"id":"read-the-signal","kind":"info","chapter":"The numbers","eyebrow":"Read the problem","title":"Every slot, the product of all the others","workspacePanel":"problem","body":["You get a list of numbers. For each slot, you report the product of every other number, leaving out the one sitting in that slot.","Two rules shape everything: no division allowed, and the work must stay O(n) for a list of up to 10^5 numbers."]},{"id":"brute-force","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Multiply the others, slot by slot","workspacePanel":"trace","summary":"It gets the right products. Watch how much each slot re-multiplies.","body":["For each slot, an inner loop walks the whole list and multiplies in every number except the one at that slot."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"answer = []\nfor i in range(len(nums)):\n    product = 1\n    for j in range(len(nums)):\n        if j != i:\n            product *= nums[j]\n    answer.append(product)\nreturn answer","steps":[{"id":"slot-zero","title":"Slot 0 walks the whole list","codeLine":6,"summary":"To fill slot 0, the inner loop multiplies 2, then 3, then 4, skipping index 0.","state":{"nums":[1,2,3,4],"i":0,"j":2}},{"id":"slot-one","title":"Slot 1 walks almost the same numbers","codeLine":2,"summary":"Slot 1 multiplies 1, then 3, then 4, re-multiplying numbers slot 0 already touched.","state":{"nums":[1,2,3,4],"i":1,"j":2}},{"id":"rewalk","title":"Slot 2 starts yet another full walk","codeLine":4,"summary":"Each new slot reopens the inner loop over the entire list, walking every number again.","state":{"nums":[1,2,3,4],"i":2,"j":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const answer = [];\nfor (let i = 0; i < nums.length; i++) {\n    let product = 1;\n    for (let j = 0; j < nums.length; j++) {\n        if (j !== i) {\n            product *= nums[j];\n        }\n    }\n    answer.push(product);\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":11},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const answer: Array<number> = [];\nfor (let i = 0; i < nums.length; i++) {\n    let product = 1;\n    for (let j = 0; j < nums.length; j++) {\n        if (j !== i) {\n            product *= nums[j];\n        }\n    }\n    answer.push(product);\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":11},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> answer = new ArrayList<>();\nfor (int i = 0; i < nums.size(); i++) {\n    int product = 1;\n    for (int j = 0; j < nums.size(); j++) {\n        if (j != i) {\n            product *= nums.get(j);\n        }\n    }\n    answer.add(product);\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":11},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> answer = new();\nfor (int i = 0; i < nums.Count; i++) {\n    int product = 1;\n    for (int j = 0; j < nums.Count; j++) {\n        if (j != i) {\n            product *= nums[j];\n        }\n    }\n    answer.Add(product);\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":11},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> answer;\nfor (int i = 0; i < nums.size(); i++) {\n    int product = 1;\n    for (int j = 0; j < nums.size(); j++) {\n        if (j != i) {\n            product *= nums[j];\n        }\n    }\n    answer.push_back(product);\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":11},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}}}}},{"id":"repeated-work","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the work","title":"For a list of n slots, how many inner multiplies run in all?","workspacePanel":"trace","summary":"Each of the n slots reopens the inner loop over the whole list.","options":[{"id":"nsquared","label":"About n slots times n numbers each, near n·n","rationale":"Every slot walks the whole list again, so the multiplies pile up to roughly n per slot across n slots: n·n work that grows with the square of the length.","isCorrect":true},{"id":"linear","label":"About n, one multiply per slot","rationale":"A slot is not one multiply: filling it walks the whole list. Each of the n slots does that, so the total is far past n."},{"id":"constant","label":"A fixed number, no matter how long the list","rationale":"The inner loop length tracks the list length, so longer lists do strictly more work. The cost is not fixed."}],"answer":"Around n·n. Each of the n slots reopens a full walk of the list, so the multiplies grow with the square of the length, the O(n^2) cost we want to beat."},{"id":"split-two","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"The product of all the others splits into which two pieces?","workspacePanel":"visualizer","summary":"For slot i, every other number is either before i or after i, with nothing in between.","options":[{"id":"left-right","label":"The product of everything to its left, times the product of everything to its right","rationale":"Everything except nums[i] is exactly the numbers before i and the numbers after i, so answer[i] is the left product times the right product.","isCorrect":true},{"id":"total-minus","label":"The total product, minus this number","rationale":"Removing a factor from a product is division, not subtraction, and division is banned here."},{"id":"neighbours","label":"The product of its two immediate neighbors","rationale":"Every index except i contributes. That means the full block before i and the full block after i both have to be included."}],"answer":"Left times right. Everything except nums[i] is the block of numbers before i and the block after i, so answer[i] is the product of the left block times the product of the right block.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"split-state","state":{"rows":[{"label":"nums","values":[2,3,4,5]}],"i":2}}]}},{"id":"one-pass-left","kind":"case-probe","chapter":"The idea","eyebrow":"Find the first pass","title":"Sweeping left to right once, what can you fill in before ever looking right?","workspacePanel":"visualizer","summary":"At slot i, a left-to-right sweep has only passed the indices before i.","options":[{"id":"left-prod","label":"Each slot's left product, the running product of everything before it","rationale":"A single forward sweep, carrying the product of everything behind the current slot, fills every slot left side. A second sweep backward does the same for the right.","isCorrect":true},{"id":"final","label":"Each slot's final answer","rationale":"The forward sweep only knows the left side. The right side is still ahead, so the answer is not complete until a second pass."},{"id":"right","label":"The right product of every slot","rationale":"Walking left to right, the numbers to the right have not been seen yet. The forward pass can only build the left products."}],"answer":"The left product. One forward sweep carrying the running product of everything behind the slot fills every left side. A backward sweep then handles the right.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-state","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,2,6],"changed":[0,1,2,3]}],"i":2}}]}},{"id":"reuse-output","kind":"case-probe","chapter":"The idea","eyebrow":"Save the space","title":"How do you fold in the right products without a second array?","workspacePanel":"visualizer","summary":"After the forward sweep, answer = [1, 1, 2, 6].","options":[{"id":"in-place","label":"Sweep backward, multiplying each slot by the running right product in place","rationale":"The slot already holds its left product, so multiplying the running right product straight into it completes the answer with no extra array.","isCorrect":true},{"id":"second-array","label":"Build a separate right-product array and add the two","rationale":"A second array works but is unnecessary, and adding products is wrong anyway; the two sides multiply. The output already has the left side to multiply into."},{"id":"divide","label":"Divide the left products back out","rationale":"Division is banned, and it is not needed: the right product multiplies cleanly into the left product already stored."}],"answer":"Multiply in place. The backward sweep carries the running right product and multiplies it into the slot that already holds the left product, so no extra array is needed.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reuse-state","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[24,12,8,6],"changed":[1]}],"i":1}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,1,1]}],"i":0}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Two sweeps over one array","workspacePanel":"visualizer","body":["answer starts as all 1s, since 1 is the identity for multiplication and leaves the first real product untouched.","The forward sweep carries a running left product: it writes the carry into each slot, then multiplies that slot number into the carry.","The backward sweep carries a running right product and multiplies it into each slot, which already holds its left product."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,1,1]}],"i":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the sweeps","title":"Trace the two passes","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,1,1]}],"i":0}},{"id":"left-pass","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,1,1],"changed":[0,1]}],"i":2,"left":2}},{"id":"right-pass","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,8,6],"changed":[2,3]}],"i":1,"right":12}}]},"beats":[{"id":"seed","title":"answer starts as [1, 1, 1, 1]. Why seed with 1s rather than 0s?","prompt":"Every slot is about to accumulate products by multiplication.","options":[{"id":"identity","label":"1 is the identity, so the first real product replaces it cleanly","rationale":"Multiplying by 1 changes nothing, so the first product written into a slot is its true left product.","isCorrect":true},{"id":"zero","label":"0 would work just as well","rationale":"Seed with 0 and every product collapses to 0, since anything times 0 is 0."},{"id":"nomatter","label":"The seed value never matters","rationale":"It matters: only 1 leaves the accumulated products correct. 0 would erase them."}],"answer":"1 is the identity for multiplication. Seed with 0 and every product becomes 0; starting at 1 lets the first multiply set the true value."},{"id":"left-pass","title":"The forward sweep reaches slot 2 (value 3). What lands in answer[2]?","prompt":"Slots 0 and 1 are already written; the carry has folded in everything before slot 2.","options":[{"id":"left","label":"The running left product, 1·2 = 2","rationale":"Each slot receives the product of everything behind it, then its own number multiplies into the carry for the next slot.","isCorrect":true},{"id":"self","label":"The value 3 itself","rationale":"The slot stores the product of the others, not its own value. Its own number only joins the carry afterward."},{"id":"full","label":"The full product 1·2·3·4","rationale":"That would include the slot own number and the numbers to its right, none of which belong in its left product yet."}],"answer":"The left product 1·2 = 2. The slot takes the carry of everything behind it, then 3 multiplies into the carry for slot 3."},{"id":"right-pass","title":"The backward sweep reaches slot 1, which already holds 1. What multiplies in?","prompt":"Slots 3 and 2 are already folded in; the right carry has passed everything after slot 1.","options":[{"id":"right","label":"The running right product, 3·4 = 12, giving 12","rationale":"Slot 1 already holds left product 1, so 1·12 = 12, which is 1·3·4, every number except nums[1].","isCorrect":true},{"id":"self","label":"nums[1] = 2","rationale":"The slot own number is exactly what must be left out, so it never multiplies into its own slot."},{"id":"left-again","label":"The left product again","rationale":"The left product is already stored. The backward sweep contributes the factors after the slot."}],"answer":"The right product 3·4 = 12. Slot 1 held left product 1, so 1·12 = 12, which is 1·3·4, all numbers except nums[1]."}]},{"id":"division-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"What if the right pass assigns the slot instead of multiplying it?","workspacePanel":"trace","summary":"The backward sweep could write `answer[i] = right` rather than `answer[i] *= right`. The first pass still ran, so the left products are sitting in the array. Watch what the assignment does to them.","pitfall":"The right pass below assigns each slot the running right product directly, instead of multiplying it into the left product already stored there.","whyItMatters":"The whole point of reusing the output array is that each slot already holds its left product when the backward sweep arrives. Assigning `answer[i] = right` throws that left product away, so every slot ends up holding only its right product. The slot must combine the two sides with `answer[i] *= right`, not replace one with the other.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"answer = [1] * len(nums)\nleft = 1\nfor i in range(len(nums)):\n    answer[i] = left\n    left *= nums[i]\nright = 1\nfor i in range(len(nums) - 1, -1, -1):\n    answer[i] = right\n    right *= nums[i]\nreturn answer","steps":[{"id":"left-stored","title":"The left pass leaves its products in the array","codeLine":5,"summary":"After the forward sweep, answer holds each slot's left product: [1, 1, 2, 6].","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,2,6]}],"i":3}},{"id":"overwrite","title":"The backward sweep overwrites slot 2","codeLine":8,"summary":"At slot 2 the right product is 4. Assigning answer[2] = 4 erases the stored left product 2 instead of forming 2·4 = 8.","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,4,1],"changed":[2]}],"i":2,"right":4}},{"id":"wrong-result","title":"The finished array is the right products alone","codeLine":10,"summary":"Every slot now holds only its right product: [24, 12, 4, 1] where the answer should be [24, 12, 8, 6].","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[24,12,4,1],"changed":[0,1,2,3]}],"i":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const answer = Array(nums.length).fill(1);\nlet left = 1;\nfor (let i = 0; i < nums.length; i++) {\n    answer[i] = left;\n    left *= nums[i];\n}\nlet right = 1;\nfor (let i = (nums.length - 1); i >= 0; i--) {\n    answer[i] = right;\n    right *= nums[i];\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const answer = Array(nums.length).fill(1);\nlet left = 1;\nfor (let i = 0; i < nums.length; i++) {\n    answer[i] = left;\n    left *= nums[i];\n}\nlet right = 1;\nfor (let i = (nums.length - 1); i >= 0; i--) {\n    answer[i] = right;\n    right *= nums[i];\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> answer = new ArrayList<>();\nfor (int index = 0; index < nums.size(); index++) {\n    answer.add(1);\n}\nint left = 1;\nfor (int i = 0; i < nums.size(); i++) {\n    answer.set(i, left);\n    left *= nums.get(i);\n}\nint right = 1;\nfor (int i = (nums.size() - 1); i >= 0; i--) {\n    answer.set(i, right);\n    right *= nums.get(i);\n}\nreturn answer;","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":10,"7":11,"8":12,"9":13,"10":15},"statementBundles":{"1":{"startLine":1,"endLine":4},"5":{"startLine":8,"endLine":9},"9":{"startLine":13,"endLine":14}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> answer = Enumerable.Repeat<int>(1, nums.Count).ToList();\nint left = 1;\nfor (int i = 0; i < nums.Count; i++) {\n    answer[i] = left;\n    left *= nums[i];\n}\nint right = 1;\nfor (int i = nums.Count - 1; i >= 0; i--) {\n    answer[i] = right;\n    right *= nums[i];\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> answer = vector<int>(nums.size(), 1);\nint left = 1;\nfor (int i = 0; i < nums.size(); i++) {\n    answer[i] = left;\n    left *= nums[i];\n}\nint right = 1;\nfor (int i = (nums.size() - 1); i >= 0; i--) {\n    answer[i] = right;\n    right *= nums[i];\n}\nreturn answer;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":12},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":11}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Two sweeps over one output array carry the left products forward and the right products back, with no division anywhere.","Now the inputs that stress a product method surface: a single zero in the list, two zeros, and the smallest list the constraints allow."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,1,1]}],"i":0}}]}},{"id":"zero-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"With one value equal to 0, which slots end up 0?","workspacePanel":"visualizer","summary":"nums = [1, 2, 0, 4].","options":[{"id":"all-but-zero","label":"Every slot except the zero own slot","rationale":"Each of those products includes the 0, so they collapse to 0. The zero own slot leaves the 0 out and holds 1·2·4 = 8.","isCorrect":true},{"id":"only-zero","label":"Only the zero own slot","rationale":"It is the reverse: the zero own slot is the one nonzero answer, because it is the only product that excludes the 0."},{"id":"all","label":"Every slot, including the zero own slot","rationale":"The zero own slot skips the 0, so it stays 1·2·4 = 8. Only the other slots, which include the 0, become 0."}],"answer":"Every slot except slot 2. Those products include the 0 and collapse to 0; slot 2 excludes it and holds 1·2·4 = 8. The two sweeps handle this with no special case, while division cannot.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-state","state":{"rows":[{"label":"nums","values":[1,2,0,4]},{"label":"answer","values":[0,0,8,0],"changed":[0,1,2,3]}],"i":2}}]}},{"id":"two-zeros-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"With two zeros in the list, what changes?","workspacePanel":"visualizer","summary":"nums = [0, 2, 0, 4], and each slot still omits only its own number.","options":[{"id":"all-zero","label":"Every slot is 0","rationale":"Each slot leaves out only its own number, so every product still includes at least one of the two remaining zeros.","isCorrect":true},{"id":"zero-slots","label":"The two zero slots become nonzero","rationale":"Slot 0 still includes the zero at index 2, and slot 2 still includes the zero at index 0, so both are 0 as well."},{"id":"one-survives","label":"Slot 1 survives","rationale":"Slot 1 multiplies 0·0·4, which includes both zeros, so it is 0 like the rest."}],"answer":"All zeros. Each slot omits only its own number, so every product keeps at least one of the two remaining zeros. With two or more zeros, the whole answer is 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-zero-state","state":{"rows":[{"label":"nums","values":[0,2,0,4]},{"label":"answer","values":[0,0,0,0],"changed":[0,1,2,3]}],"i":0}}]}},{"id":"single-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What does the smallest allowed list, two numbers, produce?","workspacePanel":"visualizer","summary":"nums = [2, 3], the shortest input the constraints permit.","options":[{"id":"swap","label":"[3, 2], each slot holding the other number","rationale":"Slot 0's left side is empty, so it starts at the identity 1 and takes only the right product 3; slot 1 takes only the left product 2. The empty side seeding as 1 is exactly what makes this work.","isCorrect":true},{"id":"same","label":"[2, 3], each slot holding its own number","rationale":"A slot reports the product of the others, not itself. With two numbers, the other number is the answer, so the two values swap."},{"id":"product","label":"[6, 6], the product of both numbers","rationale":"That includes each slot's own value. Slot 0 must exclude the 2, leaving just 3, and slot 1 must exclude the 3, leaving just 2."}],"answer":"[3, 2]. With only two numbers, each slot's product of the others is just the single number beside it, so the values swap. The empty side of each slot relies on the seed value 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-elem-state","state":{"rows":[{"label":"nums","values":[2,3]},{"label":"answer","values":[3,2],"changed":[0,1]}],"i":0}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"The output array carries every left product forward, then absorbs the right products on the way back.","body":["Make two passes over one output array: a forward sweep that hands each slot the product of everything to its left, then a backward sweep that folds in everything to its right.","Carry a single running product through each sweep so no value is ever divided and no extra array is needed."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"rows":[{"label":"nums","values":[1,2,3,4]},{"label":"answer","values":[1,1,1,1]}],"i":0}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the two-sweep product","eyebrow":"Code the rule","summary":"Build the two sweeps: seed answer with 1s, store left products, multiply in right products, and return answer.","workspacePanel":"code","checkpoints":[{"id":"init-output","title":"Initialize output for prefix products","description":"Create an output array filled with 1s so each position can accumulate products.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Starting with zeros, which would erase every product","Allocating the wrong length"],"hint":"Use 1 as the multiplication identity for every output cell.","semanticSpec":{"intent":"Initialize a same-length output sequence seeded with multiplication identity values.","doneWhen":"This step is done when a result list or array with one slot per input element exists before product passes begin.","shouldFailWhen":"This step should fail if the result is missing, scalar-only, or not sized from the input sequence.","roles":["input sequence","output sequence","multiplication identity"],"mustProve":["A result sequence is created before the product passes.","The result sequence is aligned to the input length."],"mustNotAccept":["Using a scalar total product only.","Returning the input array directly."],"equivalentVariants":["Use [1] * len(nums).","Use an equivalent same-length result initialized with neutral product values."],"proofSnippets":[{"id":"py-product-init-output","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    return answer"}]}},{"id":"left-pass","title":"Store products to the left","description":"Sweep left to right, write the running left product into answer[i], then multiply by nums[i].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"writes_forward_accumulator_to_indexed_result","scope":"left-pass","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Updating the running product before writing answer[i]","Including nums[i] in its own left product"],"hint":"At index i, answer[i] should represent values strictly before i.","semanticSpec":{"intent":"Run a left-to-right indexed pass that writes the product of values strictly to the left of each index before including the current value in the running product.","doneWhen":"This step is done when the code scans indices from the beginning, stores the current left product into the matching output slot, then updates the running product with nums[i].","shouldFailWhen":"This step should fail if the scan includes nums[i] in its own left product, updates the running product before writing the output slot, skips indices, or uses division instead of a directional product pass.","roles":["left-to-right index scan","running left product","current input value","output slot"],"mustProve":["The code performs an indexed traversal over nums from left to right or an equivalent prefix order.","At each index, the output slot receives the product accumulated before consuming nums[i].","The running left product is updated with the current value only after the slot is written."],"mustNotAccept":["Multiplying by nums[i] before writing answer[i].","Computing products by total division.","Writing a prefix product array that includes the current element for each index."],"equivalentVariants":["Use `for i in range(len(nums))` with `answer[i] = left` followed by `left *= nums[i]`.","Use an equivalent forward indexed loop that preserves the same before-current update order."],"proofSnippets":[{"id":"py-product-left-pass","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    left = 1\n    for i in range(len(nums)):\n        answer[i] = left\n        left *= nums[i]\n    return answer"}]}},{"id":"right-pass","title":"Multiply products from the right","description":"Sweep right to left with a running right product and multiply it into answer[i].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"combines_reverse_accumulator_into_indexed_result","scope":"right-pass","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Scanning from the wrong direction","Overwriting the prefix product instead of multiplying it"],"hint":"The second pass should combine, not replace, the left-side product.","semanticSpec":{"intent":"Run a right-to-left indexed pass that combines each stored left product with the product of values strictly to the right of that index.","doneWhen":"This step is done when the code scans indices from the end toward the beginning, multiplies the current output slot by the running right product, then updates the running product with nums[i].","shouldFailWhen":"This step should fail if the scan goes in the wrong direction, overwrites the stored left product instead of multiplying it, includes nums[i] in its own right product, or returns before finishing the suffix sweep.","roles":["right-to-left index scan","running right product","stored left product","combined output slot"],"mustProve":["The code performs a reverse indexed traversal over every input index.","At each index, the existing answer[i] value is multiplied by the product accumulated from indices to the right.","The running right product is updated with nums[i] only after answer[i] is combined."],"mustNotAccept":["Assigning answer[i] = right and discarding the left product.","Updating right before multiplying answer[i].","Scanning forward for the suffix pass without equivalent reversed semantics."],"equivalentVariants":["Use `for i in range(len(nums) - 1, -1, -1)` with `answer[i] *= right` followed by `right *= nums[i]`.","Use any equivalent reverse traversal that combines suffix products into the existing output array."],"neededLowerLayerFact":{"suggestedFamily":"array-scan","suggestedFact":"combines_reverse_accumulator_into_indexed_result","suggestedScope":"right-pass","owner":"Layer 5A structural facts first, then Layer 6 familyFact reader"},"proofSnippets":[{"id":"py-product-right-pass","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    left = 1\n    for i in range(len(nums)):\n        answer[i] = left\n        left *= nums[i]\n    right = 1\n    for i in range(len(nums) - 1, -1, -1):\n        answer[i] *= right\n        right *= nums[i]\n    return 0"}]}},{"id":"return-answer","title":"Return the completed output","description":"Return the output array after both directional products have been merged.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"combines_reverse_accumulator_into_indexed_result","scope":"right-pass","readMode":"array-scan-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}]},"commonMistakes":["Returning the running suffix variable","Returning before the backward pass finishes"],"hint":"The answer array is complete only after the suffix sweep reaches index 0.","semanticSpec":{"intent":"Return the completed output array after both directional product passes have contributed to every slot.","doneWhen":"This step is done when the function returns the output sequence that was initialized and updated by the left and right product passes.","shouldFailWhen":"This step should fail if the function returns a running scalar, returns too early before the reverse pass completes, returns the input array unchanged, or returns only one directional pass.","roles":["completed output array","left product contributions","right product contributions","terminal return"],"mustProve":["The returned value is the product result sequence.","The return occurs after both directional passes in the normal control-flow path."],"mustNotAccept":["Returning `left` or `right`.","Returning before the suffix pass.","Returning a prefix-only result."],"equivalentVariants":["Return `answer` after the reverse pass.","Return any same-length result array that has been populated by both directional product sweeps."],"proofSnippets":[{"id":"py-product-return-answer","language":"python","code":"def productExceptSelf(nums: list[int]) -> list[int]:\n    answer = [1] * len(nums)\n    left = 1\n    for i in range(len(nums)):\n        answer[i] = left\n        left *= nums[i]\n    right = 1\n    for i in range(len(nums) - 1, -1, -1):\n        answer[i] *= right\n        right *= nums[i]\n    return answer"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Each answer is the product of everything to its left times everything to its right.","workspacePanel":"code","body":["A forward sweep writes each slot the running product of everything before it; a backward sweep multiplies in the running product of everything after it.","The output array carries the left products between the two sweeps, so no division and no extra array are needed."],"takeaways":[{"title":"Left times right, no division","body":"Everything except a slot’s own number is the block before it and the block after it, so two running products replace the banned divide."},{"title":"The output holds the in-between state","body":"Storing left products in the answer first, then folding right products in on the way back, is what keeps the extra space at zero."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","valueRange":{"min":-30,"max":30}},"executionStyle":"solution-method"}
