{"id":"baseball-game","title":"Baseball Game","difficulty":"easy","patterns":["monotonic-stack"],"primaryConcept":"stack-lifo-validation","concepts":["stack-lifo-validation"],"problemForm":"intro","companies":["Amazon","Google"],"category":"stacks-queues","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"operations","sizeMetric":"length","sizes":[8,16,32]},"description":"You are given a list of baseball scoring operations. An integer records a new score, `\"+\"` records the sum of the previous two valid scores, `\"D\"` records double the previous valid score, and `\"C\"` removes the previous valid score. Return the sum of all valid scores after processing every operation.","examples":[{"input":"operations = [\"5\",\"2\",\"C\",\"D\",\"+\"]","output":"30","explanation":"Scores become [5], [5,2], [5], [5,10], then [5,10,15]. The total is 30."},{"input":"operations = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]","output":"27","explanation":"The stack of valid scores changes as operations add, remove, and derive records."}],"constraints":[{"id":"1-len-operations-1000","text":"1 <= len(operations) <= 1000","check":{"kind":"sizeRange","target":"operations","measure":"arrayLength","min":1,"max":1000}},{"id":"operations-i-is-an-integer-string-d-or-c","text":"operations[i] is an integer string, '+', 'D', or 'C'"},{"id":"for-there-will-always-be-at-least-two-previous-valid-scores","text":"For '+', there will always be at least two previous valid scores"},{"id":"for-d-and-c-there-will-always-be-at-least-one-previous-valid-sco","text":"For 'D' and 'C', there will always be at least one previous valid score"},{"id":"answers-fit-in-a-32-bit-signed-integer","text":"Answers fit in a 32-bit signed integer"}],"starterCode":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        # Your code here\n        pass","functionName":"calPoints","testCases":[{"id":"1","input":{"operations":["5","2","C","D","+"]},"expected":30,"description":"Canonical cancel, double, and sum operation stream."},{"id":"2","input":{"operations":["5","-2","4","C","D","9","+","+"]},"expected":27,"description":"Mixed negative score and derived records."},{"id":"3","input":{"operations":["1","C"]},"expected":0,"description":"Cancel the only valid score."},{"id":"4","input":{"operations":["3","D","D","+"]},"expected":39,"description":"Repeated doubling followed by a plus operation."},{"id":"h1","input":{"operations":["10","20","+","D","C"]},"expected":60,"description":"Cancel a derived double."},{"id":"h2","input":{"operations":["-5","-3","+","D"]},"expected":-32,"description":"Derived records from negative scores."},{"id":"h3","input":{"operations":["7","8","+","C","D","+"]},"expected":55,"description":"Cancel a plus score before deriving more records."},{"id":"h4","input":{"operations":["5","-3","D","+","C"]},"expected":-4,"description":"A cancelled plus score after a negative double."},{"id":"h5","input":{"operations":["10","C","7","D","+"]},"expected":42,"description":"A cancel followed by fresh derived scores."},{"id":"h6","input":{"operations":["9","9","+","C","D"]},"expected":36,"description":"Cancel a plus result, then double the prior valid score."}],"hints":[{"level":1,"content":"Only the most recent valid scores matter for `C`, `D`, and `+`.","revealPattern":false},{"level":2,"content":"Use a stack so you can remove the last valid score and read the previous one or two valid scores.","revealPattern":true},{"level":3,"content":"Push integer scores, pop for `C`, push double top for `D`, and push the sum of the top two scores for `+`.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"baseball-game-2026-11-20-record-to-stack","approachSelection":{"contract":"approach-selection-v1","question":"How should the scores be stored?","decisionPrompt":"Pick the plan that still cancels correctly after several C entries in a row.","approaches":[{"id":"simulate-stack","name":"Keep every score on a stack","summary":"Read the entries once and keep the scores that still count, newest on top.","decisionReason":"C, D and + only read or remove the top one or two scores, so each entry is a fixed amount of work, and every score is still stored when a C reaches it.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["O(n) time, and O(n) space because the stack can hold one score per entry."],"isOptimal":true},{"id":"running-total","name":"Keep a running total and the last score","summary":"Add each score to a total and remember only the most recent one.","decisionReason":"After one C the plan no longer holds the score before the canceled one. On 3, 8, 4, C, C it returns 7, and the right total is 3.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["O(1) space, but it can return a wrong total once an instruction after a C needs an earlier score."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-stack","title":"Start with an empty stack","description":"Create the stack that will hold the scores that still count. No entry has been read yet, so it starts empty.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"commonMistakes":["Keeping only a running total, which leaves a later C with no score to remove"],"hint":"The stack holds one number per score, with the newest score on top.","semanticSpec":{"intent":"Initialize stack state for valid scores.","doneWhen":"An empty LIFO state is available before scanning operations.","shouldFailWhen":"This step should fail if no stack-like state exists.","roles":["score stack"],"mustProve":["The solution initializes an empty stack."],"mustNotAccept":["A single running total with no score history."],"proofSnippets":[{"id":"py-baseball-init-stack","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []"}]}},{"id":"main-loop","title":"Read each entry in order","description":"Go through `operations` from first to last. Each entry changes the stack before the next one is read.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"scans_input_sequence","scope":"main-loop","readMode":"stack-value-query-v1"}]},"hint":"Every entry is handled once, and the order matters because an instruction acts on the scores that came before it.","semanticSpec":{"intent":"Scan the operation sequence once.","doneWhen":"The code loops over the input operations.","shouldFailWhen":"This step should fail if operations are not scanned.","roles":["operation sequence","current operation"],"mustProve":["The solution scans the input sequence."],"mustNotAccept":["Only handling a fixed number of operations."],"proofSnippets":[{"id":"py-baseball-main-loop","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            pass"}]}},{"id":"operator-branch","title":"Tell the instructions apart from the numbers","description":"Compare the entry with C, D and + before changing the stack. Each of the three does something different, and any other entry is a number.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"branches_on_reduction_token","scope":"operator-branch","readMode":"stack-value-query-v1"}]},"commonMistakes":["Deciding from the first character alone, which can send a negative number such as -2 down the wrong path","Converting every entry to a number, which fails on C, D and +"],"hint":"The three instructions are exact one-character entries. A number can be several characters long and can start with a minus sign.","semanticSpec":{"intent":"Branch on operator-like tokens that change stack behavior.","doneWhen":"The scan distinguishes special scoring tokens from score literals.","shouldFailWhen":"This step should fail if all tokens take the same path.","roles":["current token","operator branch"],"mustProve":["The solution branches on reduction tokens."],"mustNotAccept":["No conditional handling for special tokens."],"proofSnippets":[{"id":"py-baseball-operator-branch","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            if op == \"+\":\n                pass\n            elif op == \"D\":\n                pass\n            elif op == \"C\":\n                pass\n            else:\n                pass"}]}},{"id":"push-score","title":"Push a number as a new score","description":"When the entry is a number, convert its text to an integer and push it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_current_token_value","scope":"push-value","readMode":"stack-value-query-v1"}]},"commonMistakes":["Pushing the text of the entry where its integer value is needed"],"hint":"The entry arrives as text. The stack needs the integer it stands for, because D and + do arithmetic on it later.","semanticSpec":{"intent":"Push current score tokens onto the stack.","doneWhen":"Plain score tokens are appended to stack state.","shouldFailWhen":"This step should fail if scores are not pushed.","roles":["score token","score stack"],"mustProve":["The current token value is pushed into stack state."],"mustNotAccept":["Ignoring integer score tokens."],"proofSnippets":[{"id":"py-baseball-push-score","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            if op == \"+\":\n                pass\n            elif op == \"D\":\n                pass\n            elif op == \"C\":\n                pass\n            else:\n                stack.append(int(op))"}]}},{"id":"cancel-score","title":"Remove the top score for C","description":"C cancels the most recent score, which is the one on top of the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_resolved_stack_entry","scope":"pop-entry","readMode":"stack-value-query-v1"}]},"commonMistakes":["Removing the oldest score, at the other end of the stack"],"hint":"Exactly one score comes off, and nothing else on the stack moves.","semanticSpec":{"intent":"Pop the score stack for cancel operations.","doneWhen":"A reduction branch removes an entry from the stack.","shouldFailWhen":"This step should fail if cancel operations do not pop stack state.","roles":["cancel token","score stack"],"mustProve":["The solution pops a resolved stack entry."],"mustNotAccept":["Skipping C without changing stack state."],"proofSnippets":[{"id":"py-baseball-cancel-score","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            if op == \"+\":\n                pass\n            elif op == \"D\":\n                pass\n            elif op == \"C\":\n                stack.pop()\n            else:\n                stack.append(int(op))"}]}},{"id":"double-score","title":"Push double the top for D","description":"D adds a new score worth twice the one on top. The score it reads stays on the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_reduced_expression_result","scope":"push-double","readMode":"stack-value-query-v1"}]},"commonMistakes":["Replacing the top with its double, which loses the original score"],"hint":"Read the top without removing it, double it, and push the result.","semanticSpec":{"intent":"Push the doubled top score for D operations.","doneWhen":"The D branch appends a score derived from the current stack top.","shouldFailWhen":"This step should fail if D does not push a stack-derived value.","roles":["D token","score stack"],"mustProve":["The D branch pushes a stack-derived result."],"mustNotAccept":["Skipping D or pushing a value unrelated to the stack top."],"proofSnippets":[{"id":"py-baseball-double-score","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            if op == \"+\":\n                pass\n            elif op == \"D\":\n                stack.append(2 * stack[-1])\n            elif op == \"C\":\n                stack.pop()\n            else:\n                stack.append(int(op))"}]}},{"id":"sum-two-scores","title":"Push the sum of the top two for +","description":"The + entry adds a new score that is the sum of the top two scores. Both of them stay on the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_reduced_expression_result","scope":"push-sum","readMode":"stack-value-query-v1"}]},"commonMistakes":["Adding the two oldest scores where the two newest are needed","Leaving the two scores off the stack after reading them, so they are missing from the final total"],"hint":"Read the top two scores without removing them, add them, and push the sum.","semanticSpec":{"intent":"Push the sum for plus operations.","doneWhen":"The + branch appends a score derived from the current stack entries.","shouldFailWhen":"This step should fail if + does not push a stack-derived value.","roles":["+ token","score stack"],"mustProve":["The + branch pushes a stack-derived result."],"mustNotAccept":["Skipping + or pushing a value unrelated to the stack."],"proofSnippets":[{"id":"py-baseball-sum-two-scores","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            if op == \"+\":\n                stack.append(stack[-1] + stack[-2])\n            elif op == \"D\":\n                stack.append(2 * stack[-1])\n            elif op == \"C\":\n                stack.pop()\n            else:\n                stack.append(int(op))"}]}},{"id":"return-answer","title":"Return the total of the stack","description":"After the last entry, add up every score still on the stack and return that total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"returns_reduced_stack_value","scope":"return-answer","readMode":"stack-value-query-v1"}]},"commonMistakes":["Returning only the top score"],"hint":"An empty stack needs no special case, because its total is 0.","semanticSpec":{"intent":"Return the reduced stack outcome.","doneWhen":"The function returns the final value derived from stack state.","shouldFailWhen":"This step should fail if the return ignores the stack result.","roles":["score stack","final total"],"mustProve":["The solution returns a reduced stack value."],"mustNotAccept":["Returning an intermediate token or the raw input."],"proofSnippets":[{"id":"py-baseball-return-answer","language":"python","code":"class Solution:\n    def calPoints(self, operations: list[str]) -> int:\n        stack = []\n        for op in operations:\n            if op == \"+\":\n                stack.append(stack[-1] + stack[-2])\n            elif op == \"D\":\n                stack.append(2 * stack[-1])\n            elif op == \"C\":\n                stack.pop()\n            else:\n                stack.append(int(op))\n        return sum(stack)"}]}}],"slides":[{"id":"the-task","kind":"info","title":"Add up a game's scores from the scorekeeper's list","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"ops":["5","2","C","D","+"],"total":30,"labels":{"ops":"operations"}}}]},"body":["A game's scorekeeper wrote down a list of entries, in order. A plain number is a new score, and it goes on the record, the list of scores that count so far.","The entries C, D and + are instructions. C takes the most recent score off the record. D adds a new score that is double the most recent one. The + entry adds a new score that is the sum of the two most recent ones.","Return the total of the scores left on the record after the last entry. For the list drawn here, that total is 30."]},{"id":"dry-run-setup","kind":"info","title":"Numbers go on the record in the order they arrive","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty","title":"Before the first entry","summary":"The record is empty. The first entry, 5, is next.","state":{"ops":["5","2","C","D","+"],"i":0,"stack":[],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}},{"id":"first-score","title":"5 is a number","summary":"It goes on the record as the first score.","state":{"ops":["5","2","C","D","+"],"i":1,"stack":[5],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}},{"id":"second-score","title":"2 is a number","summary":"It goes on after the 5 and is now the newest score.","state":{"ops":["5","2","C","D","+"],"i":2,"stack":[5,2],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}}]},"body":["The entries are read once, from first to last. Each one changes the record before the next is read."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Apply C, D and + to the record","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"ops":["5","2","C","D","+"],"i":2,"stack":[5,2],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}},{"id":"cancel","state":{"ops":["5","2","C","D","+"],"i":3,"stack":[5],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}},{"id":"double","state":{"ops":["5","2","C","D","+"],"i":4,"stack":[5,10],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}},{"id":"plus","state":{"ops":["5","2","C","D","+"],"stack":[5,10,15],"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}},{"id":"total","state":{"ops":["5","2","C","D","+"],"stack":[5,10,15],"total":30,"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}}]},"beats":[{"id":"cancel","title":"C is next. What is on the record after it?","options":[{"id":"only-five","label":"Only the 5","rationale":"C takes off the most recent score, and that is the 2.","isCorrect":true},{"id":"only-two","label":"Only the 2","rationale":"That would take off the 5, the oldest score. C always takes the most recent one.","isCorrect":false},{"id":"nothing-left","label":"Nothing","rationale":"One C takes off one score. The 5 was not the most recent, so it stays.","isCorrect":false}]},{"id":"double","title":"D is next. What is on the record after it?","options":[{"id":"five-and-ten","label":"5 and 10","rationale":"The most recent score on the record is the 5, so D adds 10 after it. The 5 stays where it is.","isCorrect":true},{"id":"only-ten","label":"Only 10","rationale":"D adds a new score. It does not replace the one it doubles.","isCorrect":false},{"id":"five-and-four","label":"5 and 4","rationale":"4 would be double the 2, and the 2 is no longer on the record. D reads the record as it stands now.","isCorrect":false}]},{"id":"plus","title":"+ is next. What is on the record after it?","options":[{"id":"five-ten-fifteen","label":"5, 10 and 15","rationale":"The two most recent scores are 10 and 5, so + adds 15 after them. Both stay on the record.","isCorrect":true},{"id":"only-fifteen","label":"Only 15","rationale":"+ reads two scores and leaves them where they are. The 15 joins them as a third score.","isCorrect":false},{"id":"five-ten-seven","label":"5, 10 and 7","rationale":"7 is 5 + 2, but C already took the 2 off. The 10 counts as a score even though D made it.","isCorrect":false}]},{"id":"total","title":"After the last entry, what does the function return?","options":[{"id":"thirty","label":"30","rationale":"5 + 10 + 15 = 30. Every score still on the record counts once.","isCorrect":true},{"id":"fifteen","label":"15","rationale":"15 is only the most recent score. The function returns the total of all three.","isCorrect":false},{"id":"thirty-two","label":"32","rationale":"32 also counts the 2 that C took off. Only scores still on the record are added.","isCorrect":false}]}]},{"id":"pattern-quiz","kind":"case-probe","title":"C, D and + each used part of the record. Which part?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"final-record","state":{"ops":["5","2","C","D","+"],"stack":[5,10,15],"total":30,"labels":{"ops":"operations","i":"next","stack":"record","top":"newest"}}}]},"options":[{"id":"newest-end","label":"Only its newest end: the last score or the last two","rationale":"C took off the newest score, D doubled it, and + added the newest two. None of them reached further back.","isCorrect":true},{"id":"whole-record","label":"All of it, to work out the total again","rationale":"The total was needed once, after the last entry. No instruction along the way asked for it.","isCorrect":false},{"id":"as-written","label":"The numbers as first written, canceled ones included","rationale":"After C took off the 2, neither D nor + used it. They read what was on the record at that moment.","isCorrect":false}]},{"id":"stack-meaning","kind":"info","title":"The record is a stack","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"named","state":{"ops":["5","2","C","D","+"],"stack":[5,10,15],"total":30,"labels":{"ops":"operations","i":"next"}}}]},"body":["A list that is only read and changed at one end is called a stack. That end is the top, and the newest score is always there. Putting a new score on the top is called a push."]},{"id":"lossy-total-pitfall","kind":"info","title":"Could two numbers replace the whole stack?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"plan-start","state":{"ops":["3","8","4","C","C"],"i":3,"total":15,"last":4,"labels":{"ops":"operations","i":"next"}}}]},"body":["The function returns one number, the total, yet the stack keeps every score that still counts. A smaller plan would keep only two numbers: `total`, the sum of the scores so far, and `last`, the most recent score.","In that plan, a number is added to `total` and saved as `last`. C subtracts `last` from `total`.","Try it on a new list: 3, 8, 4, C, C. After the three numbers, `total` is 15 and `last` is 4."]},{"id":"two-number-trace","kind":"dry-run","source":"trace-example","title":"Run the two-number plan through two cancels","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"plan-setup","state":{"ops":["3","8","4","C","C"],"i":3,"total":15,"last":4,"labels":{"ops":"operations","i":"next"}}},{"id":"first-cancel","state":{"ops":["3","8","4","C","C"],"i":4,"total":11,"last":4,"labels":{"ops":"operations","i":"next"}}},{"id":"second-cancel","state":{"ops":["3","8","4","C","C"],"total":7,"last":4,"labels":{"ops":"operations","i":"next"}}}]},"beats":[{"id":"first-cancel","title":"What does the first C leave in the total?","options":[{"id":"eleven","label":"11","rationale":"15 - 4 = 11, the same as 3 + 8, the two scores that still count.","isCorrect":true},{"id":"seven","label":"7","rationale":"7 would subtract the 8. C cancels the most recent score, the 4, and that is the score in `last`.","isCorrect":false},{"id":"fifteen-still","label":"15","rationale":"C cancels the 4, so the total has to lose that 4.","isCorrect":false}]},{"id":"second-cancel","title":"The second C should cancel the 8. What can this plan subtract?","options":[{"id":"four-again","label":"Only the 4 again","rationale":"The plan stores only `total` and `last`, and `last` still holds the 4 that was already canceled. Subtracting it again gives 7, but only the 3 is left, so the right total is 3.","isCorrect":true},{"id":"last-goes-back","label":"The 8, because `last` goes back to it","rationale":"Nothing in the plan still holds the 8. It was overwritten when the 4 arrived.","isCorrect":false},{"id":"from-total","label":"The 8, worked out from the total","rationale":"The total is 11, and 11 could just as well be 5 + 6. A sum does not record which scores went into it.","isCorrect":false}]}]},{"id":"two-numbers-verdict","kind":"info","title":"Two numbers are not enough","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"stack-after-first-cancel","title":"The same list on a stack, after the first C","summary":"The 4 is gone, and the 8 is on top.","state":{"ops":["3","8","4","C","C"],"i":4,"stack":[3,8],"labels":{"ops":"operations","i":"next"}}},{"id":"stack-after-second-cancel","title":"After the second C","summary":"The 8 comes off, and the total is 3.","state":{"ops":["3","8","4","C","C"],"stack":[3],"total":3,"labels":{"ops":"operations","i":"next"}}}]},"body":["The plan wrote over the 8 when the 4 arrived, so nothing held the 8 when the second C needed it. A stack still has it.","C entries in a row can reach back to any earlier score, so every score stays on the stack until a C removes it. Keeping the last two or three scores would fail the same way on a longer run of C."]},{"id":"edge-case-intro","kind":"info","title":"Back to the stack, with three more lists to try","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example-done","state":{"ops":["5","2","C","D","+"],"stack":[5,10,15],"total":30,"labels":{"ops":"operations","i":"next"}}}]},"body":["Each one has something the first list did not. The first ends with a C right after a +. The second has a negative number in it. In the third, every score gets canceled."]},{"id":"cancel-derived-probe","kind":"case-probe","title":"A sixth entry, C, is next. What does it remove?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"extra-cancel","state":{"ops":["5","2","C","D","+","C"],"i":5,"stack":[5,10,15],"labels":{"ops":"operations","i":"next"}}}]},"options":[{"id":"only-the-sum","label":"Only the 15","rationale":"The 15 is one score on top of the stack, and C removes one score. How it got there makes no difference.","isCorrect":true},{"id":"sum-and-parts","label":"The 15, plus the 5 and 10 it was added from","rationale":"+ read the 5 and the 10 and left them in place. They are separate scores, and C removes one.","isCorrect":false},{"id":"cannot-cancel","label":"Nothing, because 15 was never written as a number","rationale":"D and + put scores on the stack the same way a number does, so C can remove them.","isCorrect":false}]},{"id":"negative-score-probe","kind":"case-probe","title":"What does the entry -2 do to the stack?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-next","state":{"ops":["5","-2","D"],"i":1,"stack":[5],"labels":{"ops":"operations","i":"next"}}}]},"options":[{"id":"push-negative","label":"-2 is pushed as a new score","rationale":"-2 is a number, so it is a score, the same as the 5, and it goes on top.","isCorrect":true},{"id":"subtract-two","label":"2 is subtracted from the 5, leaving 3","rationale":"The game has no subtract instruction. The minus sign belongs to the number.","isCorrect":false},{"id":"skip-negative","label":"It is skipped, since a score cannot be negative","rationale":"Negative scores are allowed, and they are doubled, added and canceled like any other.","isCorrect":false}]},{"id":"empty-board-probe","kind":"case-probe","title":"What should the function return when both scores were canceled?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-canceled","state":{"ops":["5","2","C","C"],"stack":[],"labels":{"ops":"operations","i":"next"}}}]},"options":[{"id":"zero","label":"0, because no scores are left to add","rationale":"A total that starts at 0 and has nothing added to it is still 0.","isCorrect":true},{"id":"error","label":"An error, because the stack is empty","rationale":"An empty stack is a normal way for a game to end: two scores, two cancels. Adding up no scores still gives a total.","isCorrect":false},{"id":"last-removed","label":"5, the last score that was removed","rationale":"A canceled score no longer counts toward anything.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"That is how to score any list. Next, you write it.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-state","state":{"ops":["5","2","C","D","+"],"stack":[],"labels":{"ops":"operations","i":"next"}}}]},"body":["The function reads the entries once, from first to last, and keeps the scores on a stack with the newest on top.","A number goes on top as a new score. C takes the top score off. D adds a new score that is double the top one, and + adds a new score that is the sum of the top two. The list is always valid, so C and D always find a score on the stack, and + always finds two.","When the list ends, the function returns the sum of the scores left on the stack."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the scoring function","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Keeping score with a stack","workspacePanel":"code","takeaways":[{"title":"Each entry is a fixed amount of work","body":"Each entry reads at most the top two scores and pushes or removes one. That work does not grow with the stack. Adding up the stack at the end is one more pass, so n entries take O(n) time."},{"title":"Every score stays until it is canceled","body":"A second C needs the score under the one the first C removed, so a running total is not enough. The stack can hold up to one score per entry, which is O(n) space."},{"title":"Scores made by D and + are ordinary scores","body":"They sit on the stack like any number from the list, so later entries can double them, add them or cancel them. Negative numbers are treated the same way."}]}],"slidesOrigin":"authored"}}
