{"id":"evaluate-reverse-polish-notation","title":"Evaluate Reverse Polish Notation","difficulty":"medium","patterns":["monotonic-stack"],"primaryConcept":"stack-lifo-validation","concepts":["stack-lifo-validation"],"problemForm":"core","companies":[],"category":"stacks-queues","executionStyle":"solution-method","compareMode":"exact","description":"Given an array of strings `tokens` representing an arithmetic expression in Reverse Polish Notation, evaluate the expression and return its integer result. The operators are `+`, `-`, `*`, and `/`. Division between two integers should truncate toward zero.","examples":[{"input":"tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]","output":"9","explanation":"((2 + 1) * 3) = 9."},{"input":"tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]","output":"6","explanation":"(4 + (13 / 5)) = 6 after truncating 13 / 5 to 2."}],"constraints":[{"id":"1-tokens-length-10000","text":"1 <= len(tokens) <= 10000","check":{"kind":"sizeRange","target":"tokens","measure":"arrayLength","min":1,"max":10000}},{"id":"each-token-is-either-an-integer-or-one-of","text":"Each token is either an integer or one of '+', '-', '*', '/'"},{"id":"the-input-is-a-valid-reverse-polish-notation-expression","text":"The input is a valid Reverse Polish Notation expression"},{"id":"intermediate-and-final-results-fit-in-a-32-bit-signed-integer","text":"Intermediate and final results fit in a 32-bit signed integer"}],"starterCode":"class Solution:\n    def evalRPN(self, tokens: list[str]) -> int:\n        # Your code here\n        pass","functionName":"evalRPN","testCases":[{"id":"1","input":{"tokens":["2","1","+","3","*"]},"expected":9,"description":"Addition followed by multiplication."},{"id":"2","input":{"tokens":["4","13","5","/","+"]},"expected":6,"description":"Division truncates before addition."},{"id":"3","input":{"tokens":["10","6","9","3","+","-11","*","/","*","17","+","5","+"]},"expected":22,"description":"Longer expression with negative values."},{"id":"4","input":{"tokens":["3","-4","+"]},"expected":-1,"description":"Addition with a negative operand."},{"id":"5","input":{"tokens":["7","-3","/"]},"expected":-2,"description":"Division truncates toward zero for negative quotients."},{"id":"6","input":{"tokens":["18"]},"expected":18,"description":"Single literal expression."},{"id":"h1","input":{"tokens":["5","1","2","+","4","*","+","3","-"]},"description":"Nested operations with both addition and subtraction.","expected":14},{"id":"h2","input":{"tokens":["-7","2","/"]},"description":"Negative division truncates toward zero.","expected":-3},{"id":"h3","input":{"tokens":["7","2","/","3","-"]},"description":"Division result feeds a later subtraction.","expected":0},{"id":"h4","input":{"tokens":["2","3","11","+","5","-","*"]},"description":"Larger intermediate stack values collapse into one result.","expected":18},{"id":"topup-1","input":{"tokens":["-10","3","/"]},"expected":-3,"description":"Top-up case 1: negative division truncates toward zero instead of flooring."},{"id":"topup-2","input":{"tokens":["8","2","/","3","4","*","+","5","-"]},"expected":11,"description":"Top-up case 2: independent subexpressions combine before a final subtraction."}],"hints":[{"level":1,"content":"Numbers wait on a stack until an operator consumes them.","revealPattern":false},{"level":2,"content":"When you see an operator, pop the right operand first, then the left operand.","revealPattern":true},{"level":3,"content":"Push each operator result back onto the stack so later operators can use it.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Pick the approach whose state matches how postfix consumes operands.","approaches":[{"id":"parse-infix","name":"Rebuild the infix expression first","summary":"Convert the postfix tokens into a parenthesized infix string or an expression tree, then evaluate that.","decisionReason":"A fully parenthesized infix reconstruction evaluates to the same result. The guided implementation reads postfix tokens directly so operator precedence needs no second expression or parser state.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Reconstructs grouping the token order already fixes, then evaluates that structure."],"isViable":true,"isOptimal":false},{"id":"reduce-with-stack","name":"Reduce tokens with a stack","summary":"Scan once, keeping every value that is still waiting for an operator and replacing consumed values with their result.","decisionReason":"A stack can grow with the backlog and shrink whenever an operator resolves part of it, so the expression can be evaluated in one pass without rebuilding an expression tree.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["One scan, with the stack holding only the values still waiting to be reduced."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-stack","title":"Start the value stack","description":"Begin with an empty stack that will hold values still waiting to be used.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Initialize a LIFO stack before token reduction begins.","doneWhen":"An empty stack exists before scanning tokens.","shouldFailWhen":"The code has no LIFO state for pending values.","roles":["value stack"],"mustProve":["empty stack initialization"],"mustNotAccept":["scalar accumulator only"],"proofSnippets":[{"id":"py-init-stack","language":"python","code":"def evalRPN(tokens):\n    stack = []"}]},"hint":"A stack of values, empty before the scan starts."},{"id":"loop-tokens","title":"Walk the tokens in order","description":"Visit each token left to right, carrying the stack along.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"scans_input_sequence","scope":"main-loop","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Scan the token sequence while carrying stack state.","doneWhen":"A loop visits each token after the stack is initialized.","shouldFailWhen":"The code only checks a fixed token or skips scanning the sequence.","roles":["token sequence","current token","value stack"],"mustProve":["sequence scan","initialized stack"],"mustNotAccept":["single-token shortcut"],"proofSnippets":[{"id":"py-loop-tokens","language":"python","code":"def evalRPN(tokens):\n    stack = []\n    for token in tokens:\n        pass"}]},"hint":"Every token is either a value to set aside or an operator that reduces."},{"id":"operator-branch","title":"Split operators from numbers","description":"Decide, per token, whether it is one of the four operators or a value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"branches_on_reduction_token","scope":"operator-branch","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Use the current token to decide whether to reduce the stack.","doneWhen":"The token loop branches on operator membership or equivalent operator checks.","shouldFailWhen":"The same action is applied to every token.","roles":["current token","operator branch"],"mustProve":["current-token branch"],"mustNotAccept":["unconditional push"],"proofSnippets":[{"id":"py-operator-branch","language":"python","code":"def evalRPN(tokens):\n    stack = []\n    for token in tokens:\n        if token in '+-*/':\n            pass"}]},"hint":"Operators reduce the stack; everything else grows it."},{"id":"push-number","title":"Set aside number tokens","description":"Turn a number token into an integer and place it on the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_current_token_value","scope":"push-value","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Push scanned value tokens onto the LIFO stack.","doneWhen":"Number tokens are converted and appended to the stack.","shouldFailWhen":"Number tokens are ignored or stored outside the stack.","roles":["current token","value stack"],"mustProve":["stack push from scanned token"],"mustNotAccept":["discarding literals"],"proofSnippets":[{"id":"py-push-number","language":"python","code":"def evalRPN(tokens):\n    stack = []\n    for token in tokens:\n        if token in '+-*/':\n            pass\n        else:\n            stack.append(int(token))"}]},"hint":"A value waits on the stack until an operator reaches for it."},{"id":"pop-operands","title":"Take the two newest values","description":"When an operator arrives, remove the newest value as the right operand and the one beneath it as the left operand.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_operands_for_reduction","scope":"pop-operands","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Pop two operand values from the stack inside the reduction branch.","doneWhen":"The operator branch pops two values from the same LIFO stack.","shouldFailWhen":"The code pops only one operand or reads operands without consuming them.","roles":["left operand","right operand","value stack"],"mustProve":["two operand pops","operator branch"],"mustNotAccept":["single-pop reduction"],"proofSnippets":[{"id":"py-pop-operands","language":"python","code":"def evalRPN(tokens):\n    stack = []\n    for token in tokens:\n        if token in '+-*/':\n            b = stack.pop()\n            a = stack.pop()\n        else:\n            stack.append(int(token))"}]},"hint":"For \"a b -\", the value taken first is the right operand b, and the next is the left operand a."},{"id":"push-result","title":"Put the result back","description":"Combine the two operands with the operator and place the single result on the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_reduced_expression_result","scope":"push-reduction","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Collapse popped operands into one stack value.","doneWhen":"The operator branch computes from the popped operands and appends the result to the same stack.","shouldFailWhen":"The code computes a value but does not push it for later operators.","roles":["operator","operands","value stack"],"mustProve":["operator reduction","result pushed to stack"],"mustNotAccept":["pop without replacement"],"proofSnippets":[{"id":"py-push-result","language":"python","code":"def evalRPN(tokens):\n    stack = []\n    for token in tokens:\n        if token in '+-*/':\n            b = stack.pop()\n            a = stack.pop()\n            if token == '+':\n                stack.append(a + b)\n        else:\n            stack.append(int(token))"}]},"hint":"Each operator turns two waiting values into one new waiting value."},{"id":"return-result","title":"Read off the final value","description":"After the scan, the answer is the one value still on the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"returns_reduced_stack_value","scope":"return-answer","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Return the final reduced value from the stack.","doneWhen":"The function returns the stack-derived value after the scan finishes.","shouldFailWhen":"The code returns the stack object, a token, or an intermediate operand.","roles":["value stack","final result"],"mustProve":["terminal stack return"],"mustNotAccept":["returning unreduced stack"],"proofSnippets":[{"id":"py-return-result","language":"python","code":"def evalRPN(tokens):\n    stack = []\n    for token in tokens:\n        if token in '+-*/':\n            b = stack.pop()\n            a = stack.pop()\n            if token == '+':\n                stack.append(a + b)\n        else:\n            stack.append(int(token))\n    return stack.pop()"}]},"hint":"A valid postfix expression leaves exactly one value behind."}],"slides":[{"id":"the-task","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Evaluate the expression with no parentheses","workspacePanel":"problem","body":["Evaluate a list of Reverse Polish Notation tokens and return its integer result. Each operator appears after the two values it combines, and division truncates toward zero.","An operator consumes the two most recent unfinished values. Their order still matters for subtraction and division, so both values must remain available until the operator arrives."]},{"id":"accumulator-fails","kind":"code-trace","chapter":"The problem","eyebrow":"The obvious way","title":"Fold left with one running total?","summary":"Keep one running total and apply each operator to it as the operator appears. Simple chains come out right, but watch it on [\"4\",\"13\",\"5\",\"/\",\"+\"], where the first operator needs two numbers it has not combined yet.","workspacePanel":"trace","body":["One number, total, updated as each operator is read left to right."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"total = int(tokens[0])\nlast = None\nfor token in tokens[1:]:\n    if token == \"+\":\n        total = total + last\n    elif token == \"/\":\n        total = int(total / last)\n    else:\n        last = int(token)\nreturn total","steps":[{"id":"seed","title":"Seed the total with the first number","codeLine":1,"summary":"total starts at 4. So far one number is held, and nothing has gone wrong.","state":{"nums":["4","13","5","/","+"],"i":0,"total":4,"labels":{"nums":"tokens"}}},{"id":"stash-numbers","title":"Two numbers arrive, but only one slot holds them","codeLine":9,"summary":"13 then 5 are both non-operators. With room for a single held number, last ends up 5 and 13 is already overwritten, though the next operator was meant for 13 and 5.","state":{"nums":["4","13","5","/","+"],"i":2,"total":4,"last":5,"labels":{"nums":"tokens"}}},{"id":"wrong-divide","title":"The operator combines the wrong pair","codeLine":7,"summary":"/ fires on total and last, computing 4 / 5 instead of 13 / 5. One running total can hold a chain of results but never a backlog of operands waiting their turn.","state":{"nums":["4","13","5","/","+"],"i":3,"total":0.8,"last":5,"labels":{"nums":"tokens"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let total = Number.parseInt(tokens[0], 10);\nlet last = null;\nfor (const token of tokens.slice(1)) {\n    if (token === \"+\") {\n        total = total + last;\n    } else {\n        if (token === \"/\") {\n            total = Math.trunc((total / last));\n        } else {\n            last = Number.parseInt(token, 10);\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let total = Number.parseInt(tokens[0], 10);\nlet last = null;\nfor (const token of tokens.slice(1)) {\n    if (token === \"+\") {\n        total = total + last;\n    } else {\n        if (token === \"/\") {\n            total = Math.trunc((total / last));\n        } else {\n            last = Number.parseInt(token, 10);\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int total = Integer.parseInt(tokens.get(0));\nInteger last = null;\nfor (String token : new ArrayList<String>(tokens.subList(1, tokens.size()))) {\n    if (\"+\".equals(token)) {\n        total = total + last;\n    } else {\n        if (\"/\".equals(token)) {\n            total = total / last;\n        } else {\n            last = Integer.parseInt(token);\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int total = int.Parse(tokens[0]);\nint last = 0;\nforeach (string token in tokens.GetRange(1, tokens.Count - 1)) {\n    if (token == \"+\") {\n        total = total + last;\n    } else {\n        if (token == \"/\") {\n            total = total / last;\n        } else {\n            last = int.Parse(token);\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int total = stoi(tokens[0]);\nint last = 0;\nfor (string token : vector<string>(tokens.begin() + 1, tokens.begin() + tokens.size())) {\n    if (token == string(\"+\")) {\n        total = total + last;\n    } else {\n        if (token == string(\"/\")) {\n            total = static_cast<int>((total / last));\n        } else {\n            last = stoi(token);\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"9":{"startLine":10,"endLine":13}}}}}},{"id":"what-accumulator-misses","kind":"case-probe","chapter":"The problem","eyebrow":"Name the gap","title":"What could a single total not hold?","workspacePanel":"trace","options":[{"id":"pending","label":"A backlog of operands waiting for their operator","rationale":"Numbers pile up before the operator that uses them, and the count of waiting numbers grows and shrinks. One slot cannot hold a growing pile.","isCorrect":true},{"id":"more-ops","label":"It just needs to apply each operator twice","rationale":"The operator was not skipped; it ran on the wrong pair. Running it again still combines whatever single number was kept.","isCorrect":false},{"id":"precision","label":"It loses precision rounding the division","rationale":"Truncation is the defined behavior here. 4 / 5 is wrong because 4 was never an operand of that division at all.","isCorrect":false}],"answer":"It cannot hold the pile of numbers still waiting for an operator. The fix is a memory that keeps every pending value.","summary":"13 and 5 both arrived before any operator, but only one number could be kept."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which approach should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,13,5],"stackActive":[1,2],"labels":{"nums":"tokens","i":"token"}}}]}},{"id":"pending-needs-a-rule","kind":"info","chapter":"The idea","eyebrow":"From one slot to many","title":"Keep every waiting value, then decide who gets consumed","workspacePanel":"visualizer","body":["One slot failed because several numbers can wait at once: 13 and 5 both arrived before any operator. The memory has to hold the whole backlog.","Holding the backlog raises a second question, the access rule: when an operator finally fires, which of the waiting values does it consume?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"waiting-stack","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,13,5],"stackActive":[],"labels":{"nums":"tokens","i":"token"}}}]}},{"id":"which-two-values","kind":"case-probe","chapter":"The idea","eyebrow":"Name the rule","title":"When an operator fires, which two waiting values does it take?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"which-two","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,13,5],"stackActive":[],"labels":{"nums":"tokens","i":"token"}}}]},"options":[{"id":"two-newest","label":"The two most recently added: 13 and 5","rationale":"In postfix an operator always closes the most recently finished pair. 13 and 5 are the newest two waiting, so / combines them and leaves 4 untouched.","isCorrect":true},{"id":"two-oldest","label":"The two oldest: 4 and 13","rationale":"Taking the oldest pair would compute 4 / 13 and ignore the 5 that was placed right before the operator, which is the opposite of how postfix groups.","isCorrect":false},{"id":"all-three","label":"All three waiting values at once","rationale":"A binary operator takes exactly two operands. Folding in 4 as well would change division into something with three inputs.","isCorrect":false}],"answer":"The two newest waiting values, 13 and 5. Storing values newest-on-top means an operator always reaches for the top two: a stack.","summary":"On [\"4\",\"13\",\"5\",\"/\",\"+\"], the / arrives with 4, 13, and 5 all waiting."},{"id":"which-is-right","kind":"case-probe","chapter":"The idea","eyebrow":"Name the rule","title":"Of the two values taken, which is the right operand?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"which-right","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,13,5],"stackActive":[2],"labels":{"nums":"tokens","i":"token"}}}]},"options":[{"id":"top-right","label":"The top value, 5, is the right operand","rationale":"The value placed last sits on top and is the right-hand side of the operator, so / computes 13 / 5 = 2. The same pop order controls subtraction.","isCorrect":true},{"id":"top-left","label":"The top value, 5, is the left operand","rationale":"Reading the top as the left operand computes 5 / 13 = 0, flipping every non-commutative operation. The newer value is the right side.","isCorrect":false},{"id":"no-matter","label":"It does not matter which is which","rationale":"+ and * give the same result in either order. Division does not: 13 / 5 = 2 while 5 / 13 = 0. Subtraction has the same operand-order requirement.","isCorrect":false}],"answer":"The top value is the right operand. The newest value, 5, is the right side, so / computes 13 / 5 = 2, not 5 / 13 = 0.","summary":"The / operator has just popped 5 and 13 from the stack."},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it reduce","title":"Numbers wait, operators collapse","workspacePanel":"visualizer","body":["Use the rule you earned: numbers wait on the stack, an operator reduces the newest two values with the value on top as its right operand, and the result waits in their place.","The numbers in [\"4\",\"13\",\"5\",\"/\",\"+\"] are already on the stack. Predict the next collapses as / and then + fire."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,13,5],"stackActive":[],"labels":{"nums":"tokens","i":"token"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Reduce the stack","title":"Reduce 4, 13, 5, /, +","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-waiting","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,13,5],"stackActive":[2],"labels":{"nums":"tokens","i":"token"}}},{"id":"after-divide","state":{"nums":["4","13","5","/","+"],"i":3,"stack":[4,2],"stackActive":[1],"labels":{"nums":"tokens","i":"token"}}},{"id":"after-add","state":{"nums":["4","13","5","/","+"],"i":4,"stack":[6],"stackActive":[0],"labels":{"nums":"tokens","i":"token"}}}]},"beats":[{"id":"three-waiting","title":"Three numbers are waiting and / is next. Which pair does it take?","summary":"4, 13, and 5 have each been pushed; the / is the next token.","prompt":"4, 13, and 5 sit on the stack, newest on top, and / is about to fire.","options":[{"id":"top-two","label":"The top two, 13 and 5, with 5 as the right operand","rationale":"An operator reduces the newest pair. 13 and 5 are taken, 5 is the right operand, so / computes 13 / 5 and 4 stays put beneath.","isCorrect":true},{"id":"bottom-two","label":"The bottom two, 4 and 13","rationale":"That ignores the 5 pushed immediately before the operator. Postfix combines the most recent pair.","isCorrect":false},{"id":"flip","label":"The top two, but with 5 as the left operand","rationale":"5 on top is the right operand, so the result is 13 / 5 = 2. Reading it as the left side would give 5 / 13 = 0.","isCorrect":false}],"answer":"It takes 13 and 5 with 5 as the right operand, computes 13 / 5 = 2, and 4 is left waiting."},{"id":"after-divide","title":"After /, the stack holds 4 and 2. What does + do next?","summary":"The division has reduced three values to two: 4 sits beneath the fresh 2.","prompt":"The stack is 4 then 2, newest on top, and + is the final token.","options":[{"id":"add-pair","label":"Take 4 and 2 and push 6","rationale":"The result of / became a normal waiting value, so + reduces the newest pair, 4 and 2, into 4 + 2 = 6.","isCorrect":true},{"id":"leave-result","label":"Leave the 2 out since it came from an operator","rationale":"A pushed result is indistinguishable from a literal once on the stack; + treats 2 like any other waiting value.","isCorrect":false},{"id":"append-token","label":"Add the digits of the next token instead","rationale":"+ here is an operator. It combines the two values already waiting.","isCorrect":false}],"answer":"It takes 4 and 2 and pushes 4 + 2 = 6, collapsing the stack to a single value."},{"id":"after-add","title":"When the scan ends, where does the answer come from?","summary":"Every token has been consumed and the visualizer shows the stack after the last reduction.","prompt":"No tokens are left to read.","options":[{"id":"lone-value","label":"The one remaining value, 6","rationale":"A valid postfix expression reduces to exactly one value, and that lone value on the stack is the answer.","isCorrect":true},{"id":"sum-stack","label":"The sum of everything still on the stack","rationale":"Only one value remains, so there is nothing to sum; reducing already combined every operand.","isCorrect":false},{"id":"last-token","label":"The last token read, +","rationale":"+ was an operator that has already done its work; the result is the value it produced.","isCorrect":false}],"answer":"The lone value, 6. A valid expression always leaves exactly one value, and that is the result."}]},{"id":"truncation-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Can the divide just floor the real quotient?","workspacePanel":"trace","summary":"Compute the true quotient and round it down with floor: it looks fine on every positive quotient. A negative quotient is where two rounding rules part ways. Watch [\"-7\",\"3\",\"/\"] reduce.","pitfall":"The code below reduces / by flooring the real quotient instead of truncating it toward zero.","whyItMatters":"Flooring rounds toward negative infinity while the problem asks for truncation toward zero, and the two split only when the quotient is negative. For -7 over 3 the real quotient is about -2.33: truncating gives -2, but flooring drops to -3. The fix is to compute the quotient and then truncate toward zero, not round it down.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def divide_top(stack: list[int]) -> list[int]:\n    import math\n    right = stack.pop()\n    left = stack.pop()\n    result = math.floor(left / float(right))\n    stack.append(result)\n    return stack","steps":[{"id":"before-divide","title":"Before /: -7 and 3 are waiting","codeLine":3,"summary":"s = [\"-7\",\"3\",\"/\"]. The two numbers are on the stack, 3 newest on top, and / is next.","state":{"nums":["-7","3","/"],"i":2,"stack":[-7,3],"stackActive":[1],"labels":{"nums":"tokens","i":"token"}}},{"id":"take-operands","title":"Take 3 as the right operand and -7 as the left","codeLine":4,"summary":"The newest value 3 is the right operand, -7 is the left, so the divide is -7 over 3.","state":{"nums":["-7","3","/"],"i":2,"stack":[],"left":-7,"right":3,"labels":{"nums":"tokens","i":"token"}}},{"id":"floor-divide","title":"Floor division rounds the wrong way","codeLine":5,"summary":"-7 divided by 3 is about -2.33. Truncating toward zero is -2, but flooring drops to -3.","state":{"nums":["-7","3","/"],"i":2,"stack":[],"left":-7,"right":3,"result":-3,"labels":{"nums":"tokens","i":"token"}}},{"id":"wrong-pushed","title":"A -3 is pushed where -2 belongs","codeLine":6,"summary":"The stack now carries -3, so the function returns -3 for an expression whose answer is -2.","state":{"nums":["-7","3","/"],"i":3,"stack":[-3],"stackActive":[0],"labels":{"nums":"tokens","i":"token"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const right = stack.pop();\nconst left = stack.pop();\nconst result = Math.floor((left / Number(right)));\nstack.push(result);\nreturn stack;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":5},"alternateStyles":{"close-to-source":{"code":"const poppedValue = stack.pop();\nif (poppedValue === undefined) throw new Error(\"IndexError\");\nconst right = poppedValue;\nconst poppedValue2 = stack.pop();\nif (poppedValue2 === undefined) throw new Error(\"IndexError\");\nconst left = poppedValue2;\nconst result = Math.floor((left / Number(right)));\nstack.push(result);\nreturn stack;","lineMap":{"3":1,"4":4,"5":7,"6":8,"7":9},"statementBundles":{"3":{"startLine":1,"endLine":3},"4":{"startLine":4,"endLine":6}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const right = stack.pop()!;\nconst left = stack.pop()!;\nconst result = Math.floor((left / Number(right)));\nstack.push(result);\nreturn stack;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":5},"alternateStyles":{"close-to-source":{"code":"const poppedValue = stack.pop();\nif (poppedValue === undefined) throw new Error(\"IndexError\");\nconst right = poppedValue;\nconst poppedValue2 = stack.pop();\nif (poppedValue2 === undefined) throw new Error(\"IndexError\");\nconst left = poppedValue2;\nconst result = Math.floor((left / Number(right)));\nstack.push(result);\nreturn stack;","lineMap":{"3":1,"4":4,"5":7,"6":8,"7":9},"statementBundles":{"3":{"startLine":1,"endLine":3},"4":{"startLine":4,"endLine":6}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int right = stack.remove(stack.size() - 1);\nint left = stack.remove(stack.size() - 1);\nint result = (int)Math.floor(((double)left / (double)(right)));\nstack.add(result);\nreturn stack;","lineMap":{"3":1,"4":2,"5":3,"6":4,"7":5}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int right = stack[stack.Count - 1];\nstack.RemoveAt(stack.Count - 1);\nint left = stack[stack.Count - 1];\nstack.RemoveAt(stack.Count - 1);\nint result = checked((int)Math.Floor((left / (double)right)));\nstack.Add(result);\nreturn stack;","lineMap":{"3":1,"4":3,"5":5,"6":6,"7":7},"statementBundles":{"3":{"startLine":1,"endLine":2},"4":{"startLine":3,"endLine":4}},"alternateStyles":{"close-to-source":{"code":"int right = stack[stack.Count - 1];\nstack.RemoveAt(stack.Count - 1);\nint left = stack[stack.Count - 1];\nstack.RemoveAt(stack.Count - 1);\nint result = Convert.ToInt32(Math.Floor(Convert.ToDouble(left / (double)right)));\nstack.Add(result);\nreturn stack;","lineMap":{"3":1,"4":3,"5":5,"6":6,"7":7},"statementBundles":{"3":{"startLine":1,"endLine":2},"4":{"startLine":3,"endLine":4}}}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int right = stack_.back();\nstack_.pop_back();\nint left = stack_.back();\nstack_.pop_back();\nint result = static_cast<int>(floor((left / static_cast<double>(right))));\nstack_.push_back(result);\nreturn stack_;","lineMap":{"3":1,"4":3,"5":5,"6":6,"7":7},"statementBundles":{"3":{"startLine":1,"endLine":2},"4":{"startLine":3,"endLine":4}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The reduce loop handles long expressions cleanly, so the cases that bite are the short and oddly shaped ones, where the stack barely fills.","Two are worth a look before coding: an expression that is just one number, where no operator ever fires, and a token like \"-4\" whose leading dash could be read two ways."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":["18"],"i":0,"stack":[],"stackActive":[],"labels":{"nums":"tokens","i":"token"}}}]}},{"id":"single-literal-probe","kind":"case-probe","chapter":"Edge cases","eyebrow":"Force a decision","title":"What does a lone number token return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-literal-state","state":{"nums":["18"],"i":0,"stack":[18],"stackActive":[0],"labels":{"nums":"tokens","i":"token"}}}]},"options":[{"id":"final-value","label":"18, read as the one value left on the stack","rationale":"Reading the answer as the leftover stack value needs no operator to have run, so a single literal returns itself with no special case.","isCorrect":true},{"id":"needs-op","label":"Nothing valid, since no operator ran","rationale":"A single number is a valid expression; the result is just that number. Requiring an operator would reject legal input.","isCorrect":false},{"id":"zero","label":"0, the empty starting total","rationale":"There is no running total seeded to zero; 18 was pushed and remains, so the leftover value is 18.","isCorrect":false}],"answer":"It returns 18: the lone value left on the stack. Reading the result from the stack covers this for free.","summary":"tokens = [\"18\"]: the scan pushes 18 and then there are no more tokens."},{"id":"negative-literal-probe","kind":"case-probe","chapter":"Edge cases","eyebrow":"Force a decision","title":"Is \"-4\" an operator or a value?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-literal-state","state":{"nums":["3","-4","+"],"i":1,"stack":[3],"stackActive":[0],"labels":{"nums":"tokens","i":"token"}}}]},"options":[{"id":"value","label":"A value: push -4, then + adds 3 and -4 to get -1","rationale":"Only the four exact symbols + - * / are operators. \"-4\" is a number, so it is pushed, and + then reduces 3 and -4 into -1.","isCorrect":true},{"id":"operator","label":"The minus operator, because it starts with a dash","rationale":"Treating \"-4\" as subtraction would try to reduce with only one value waiting. The token is the whole string \"-4\", a negative number.","isCorrect":false},{"id":"skip","label":"Skip it, since a negative cannot be on the stack","rationale":"Negative values are ordinary operands here; skipping -4 would drop an operand the + still needs.","isCorrect":false}],"answer":"It is a value. Branching only on the exact symbols + - * / pushes \"-4\" as -4, and + then yields 3 + (-4) = -1.","summary":"tokens = [\"3\",\"-4\",\"+\"]: the second token is \"-4\", a dash followed by a digit."},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The stack carries pending values; for an operator, pop the right operand before the left operand.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Walk the tokens once, keeping a stack of values still waiting. A number joins the stack; an operator reduces the newest two values, with the value on top as its right operand, and the result rejoins the stack.","When the tokens run out, the one value left on the stack is the answer, and a negative quotient must truncate toward zero rather than round down."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":["4","13","5","/","+"],"i":0,"stack":[],"stackActive":[],"labels":{"nums":"tokens","i":"token"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the postfix reducer","summary":"Now build it: start an empty stack and walk the tokens in order, splitting operators from numbers; push each number, and on an operator pop the newest two values with the top as the right operand, combine them, and push the result, then read the single leftover value at the end.","workspacePanel":"code"},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"An operator always reduces the two newest pending values, newest as its right operand.","body":["Postfix encodes grouping in the order of the tokens, so a single left-to-right scan with a stack recovers it without rebuilding any parentheses.","The stack is the backlog of operands waiting for an operator, which is the piece a single running total could never hold."],"takeaways":[{"title":"The newest two are the operands","body":"Each operator reduces the top two values, with the value on top as its right operand, then pushes the result back as a fresh pending value."},{"title":"Pop right before left","body":"For [\"4\",\"13\",\"5\",\"/\",\"+\"], reading the top as the right operand gives 13 / 5 = 2; flipping it gives 5 / 13 = 0 and the wrong total."},{"title":"Truncate division toward zero","body":"A negative quotient like -7 over 3 is -2, not -3, so divide and then truncate toward zero rather than reaching for floor division."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"timeComplexity":"O(n)","spaceComplexity":"O(n)"}
