{"id":"min-stack","title":"Min Stack","difficulty":"medium","patterns":["monotonic-stack"],"primaryConcept":"stack-lifo-validation","concepts":["stack-lifo-validation"],"problemForm":"core","companies":[],"category":"stacks-queues","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","secondaryParam":"arguments","sizeMetric":"op-count","opVocabulary":[{"name":"MinStack","arity":0,"weight":1},{"name":"push","arity":1,"argTypes":["integer"],"weight":4},{"name":"pop","arity":0,"weight":2},{"name":"top","arity":0,"weight":2},{"name":"getMin","arity":0,"weight":2}]},"description":"Design a stack that supports `push`, `pop`, `top`, and `getMin` in constant time. `getMin` should return the minimum value currently in the stack.","examples":[{"input":"operations = [\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\narguments = [[],[-2],[0],[-3],[],[],[],[]]","output":"[null,null,null,null,-3,null,0,-2]","explanation":"The minimum becomes -3 after pushing it, then returns to -2 after popping."},{"input":"operations = [\"MinStack\",\"push\",\"top\",\"getMin\"]\narguments = [[],[-10],[],[]]","output":"[null,null,-10,-10]","explanation":"With one value, both top and getMin return that value."}],"constraints":[{"id":"2-31-val-2-31-1","text":"-2^31 <= val <= 2^31 - 1"},{"id":"pop-top-and-getmin-are-called-only-on-non-empty-stacks","text":"pop, top, and getMin are called only on non-empty stacks"},{"id":"at-most-30000-calls-will-be-made-to-push-pop-top-and-getmin","text":"At most 30000 calls will be made to push, pop, top, and getMin"},{"id":"each-operation-must-run-in-o-1-time","text":"Each operation must run in O(1) time"}],"starterCode":"class MinStack:\n    def __init__(self):\n        # Your code here\n        pass\n\n    def push(self, val: int) -> None:\n        # Your code here\n        pass\n\n    def pop(self) -> None:\n        # Your code here\n        pass\n\n    def top(self) -> int:\n        # Your code here\n        pass\n\n    def getMin(self) -> int:\n        # Your code here\n        pass","functionName":"MinStack","testCases":[{"id":"1","input":{"operations":["MinStack","push","push","push","getMin","pop","top","getMin"],"arguments":[[],[-2],[0],[-3],[],[],[],[]]},"expected":[null,null,null,null,-3,null,0,-2],"description":"Canonical min-stack operation stream."},{"id":"2","input":{"operations":["MinStack","push","push","getMin","top","pop","getMin"],"arguments":[[],[5],[1],[],[],[],[]]},"expected":[null,null,null,1,1,null,5],"description":"Minimum changes after popping the top minimum."},{"id":"3","input":{"operations":["MinStack","push","push","push","getMin","pop","getMin","pop","getMin"],"arguments":[[],[2],[2],[3],[],[],[],[],[]]},"expected":[null,null,null,null,2,null,2,null,2],"description":"Duplicate minimum values remain valid after pops."},{"id":"4","input":{"operations":["MinStack","push","top","getMin"],"arguments":[[],[-10],[],[]]},"expected":[null,null,-10,-10],"description":"Single-element stack."},{"id":"h1","input":{"operations":["MinStack","push","push","top","getMin","pop","getMin"],"arguments":[[],[1],[2],[],[],[],[]]},"description":"Minimum updates after popping the top value.","expected":[null,null,null,2,1,null,1]},{"id":"h2","input":{"operations":["MinStack","push","push","push","getMin","pop","getMin","pop","top"],"arguments":[[],[2],[0],[2],[],[],[],[],[]]},"description":"Duplicate minima remain valid after removing a later copy.","expected":[null,null,null,null,0,null,0,null,2]},{"id":"h3","input":{"operations":["MinStack","push","pop","push","top","getMin"],"arguments":[[],[3],[],[4],[],[]]},"description":"Popping down to an empty stack and rebuilding it.","expected":[null,null,null,null,4,4]},{"id":"h4","input":{"operations":["MinStack","push","push","push","getMin","pop","top","getMin"],"arguments":[[],[5],[1],[6],[],[],[],[]]},"description":"A lower middle element stays as the minimum after a pop.","expected":[null,null,null,null,1,null,1,1]},{"id":"h5","input":{"operations":["MinStack","push","push","getMin","pop","top","getMin"],"arguments":[[],[-1],[-2],[],[],[],[]]},"description":"Negative values keep the running minimum simple to check.","expected":[null,null,null,-2,null,-1,-1]},{"id":"h6","input":{"operations":["MinStack","push","push","push","top","getMin","pop","top","getMin"],"arguments":[[],[10],[7],[8],[],[],[],[],[]]},"description":"Top and minimum diverge after a non-minimum pop.","expected":[null,null,null,null,8,7,null,7,7]},{"id":"integer-boundaries","input":{"operations":["MinStack","push","push","getMin","top","pop","top","getMin"],"arguments":[[],[-2147483648],[2147483647],[],[],[],[],[]]},"description":"The stack handles integer boundary values while preserving the minimum.","expected":[null,null,null,-2147483648,2147483647,null,-2147483648,-2147483648]},{"id":"alternating-minimum-pops","input":{"operations":["MinStack","push","push","push","getMin","pop","getMin","pop","getMin","top"],"arguments":[[],[3],[1],[2],[],[],[],[],[],[]]},"description":"Minimum values update correctly while popping back through the stack.","expected":[null,null,null,null,1,null,1,null,3,3]}],"hints":[{"level":1,"content":"Keep the normal stack and a second stack that tracks the minimum at each depth.","revealPattern":false},{"level":2,"content":"On push, store the smaller of the new value and the previous minimum.","revealPattern":true},{"level":3,"content":"On pop, remove from both stacks so their depths stay aligned.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which design keeps getMin constant while push and pop stay constant too?","decisionPrompt":"Pick the design whose getMin reads a ready answer instead of searching for it.","approaches":[{"id":"scan-on-getmin","name":"Scan the stack on every getMin","summary":"Keep one stack of values and walk all of them to find the smallest each time getMin is called.","decisionReason":"The single stack returns the right answer, but getMin walks every value, so a deep stack queried often does work that grows with its depth on each call.","complexity":{"time":"O(n) getMin","space":"O(n)"},"tradeoffs":["getMin walks the whole stack, so its cost grows with the number of stored values."],"isOptimal":false},{"id":"parallel-min-stack","name":"Carry a paired minimum stack","summary":"Beside the value stack, keep a second stack whose top is always the minimum of everything currently stored.","decisionReason":"Each push records the smaller of the new value and the previous minimum, so getMin reads the top of the minimum stack and a pop discards both tops together, all in constant time.","complexity":{"time":"O(1) per operation","space":"O(n)"},"tradeoffs":["A second stack of equal depth, in exchange for constant-time getMin."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-state","title":"Initialize the two stacks","description":"Create a value stack and a matching minimum stack in the constructor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"initializes_parallel_sequence_state","scope":"init-state","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Initialize parallel sequence-backed instance state.","doneWhen":"The constructor creates at least two empty sequence fields on the instance.","shouldFailWhen":"The class has only one stack or uses only local state.","roles":["value stack","minimum stack"],"mustProve":["parallel sequence state initialized"],"mustNotAccept":["single stack only"],"proofSnippets":[{"id":"py-init-state","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        pass\n\n    def pop(self):\n        pass\n\n    def top(self):\n        pass\n\n    def getMin(self):\n        pass"}]},"hint":"Both stacks should start empty and have matching depths."},{"id":"push-value","title":"Push the value","description":"Append the new value to the main stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"pushes_primary_sequence_value","scope":"push-value","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Store the pushed value in the primary instance stack.","doneWhen":"The push method appends its input value to an instance sequence field.","shouldFailWhen":"The value is not persisted on the object.","roles":["push value","value stack"],"mustProve":["method parameter pushed to instance state"],"mustNotAccept":["discarding the pushed value"],"proofSnippets":[{"id":"py-push-value","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)"}]},"hint":"The ordinary stack still needs every pushed value."},{"id":"push-min","title":"Update the minimum stack","description":"Append the current minimum for this stack depth.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"pushes_derived_extremum_state","scope":"push-derived","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Push a derived minimum value into a parallel instance sequence.","doneWhen":"The push method appends the min of the new value and the previous minimum top.","shouldFailWhen":"The min state is updated only when the value decreases or is recomputed by scanning.","roles":["minimum stack","new value","previous minimum"],"mustProve":["derived extremum push"],"mustNotAccept":["missing duplicate-depth minimum entry"],"proofSnippets":[{"id":"py-push-min","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))"}]},"hint":"Store the minimum for the new depth every time you push."},{"id":"pop-both","title":"Pop both stacks","description":"Remove one entry from the value stack and the minimum stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"pops_parallel_sequence_state","scope":"pop-method","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Keep parallel stack depths synchronized on pop.","doneWhen":"The pop method removes from both instance sequence fields.","shouldFailWhen":"Only the value stack is popped or the min stack can become stale.","roles":["value stack","minimum stack"],"mustProve":["paired instance pops"],"mustNotAccept":["popping one stack only"],"proofSnippets":[{"id":"py-pop-both","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))\n\n    def pop(self):\n        self.stack.pop()\n        self.min_stack.pop()"}]},"hint":"The min stack has one entry per value stack entry."},{"id":"top-method","title":"Return the value stack top","description":"Return the most recently pushed value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"returns_primary_sequence_top","scope":"top-method","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Expose the top of the primary value stack.","doneWhen":"The top method returns the top entry from the primary pushed-value field.","shouldFailWhen":"The method returns the minimum stack top or another value.","roles":["value stack top"],"mustProve":["primary sequence top return"],"mustNotAccept":["returning current minimum"],"proofSnippets":[{"id":"py-top-method","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))\n\n    def pop(self):\n        self.stack.pop()\n        self.min_stack.pop()\n\n    def top(self):\n        return self.stack[-1]"}]},"hint":"top reads from the ordinary value stack."},{"id":"get-min-method","title":"Return the minimum stack top","description":"Return the current minimum in O(1).","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"returns_derived_extremum_top","scope":"extremum-method","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Expose the top of the derived minimum stack.","doneWhen":"getMin returns the top entry from the derived extremum field.","shouldFailWhen":"getMin scans the value stack or returns the latest value.","roles":["minimum stack top"],"mustProve":["derived extremum top return"],"mustNotAccept":["linear scan for minimum"],"proofSnippets":[{"id":"py-get-min-method","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))\n\n    def pop(self):\n        self.stack.pop()\n        self.min_stack.pop()\n\n    def top(self):\n        return self.stack[-1]\n\n    def getMin(self):\n        return self.min_stack[-1]"}]},"hint":"getMin reads from the minimum stack, not from the value stack."}],"slides":[{"id":"read-the-problem","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"A stack that also reports its smallest value","workspacePanel":"problem","body":["Build a stack with the usual push, pop, and top, plus one extra: getMin returns the smallest value currently held. Every one of the four has to finish in constant time, however deep the stack grows.","Push -2, then 0, then -3, and the stack holds -2, 0, -3 with -3 on top. top is -3 and getMin is -3. Pop the -3, and top becomes 0 while getMin drops back to -2, the smallest of what is left.","The plain way to answer getMin is to look through every stored value for the smallest. Watch that work, then watch the cost of doing it on every call."]},{"id":"scan-getmin","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Find the minimum by scanning the stack","summary":"push and pop stay simple on one stack, but getMin walks every value to find the smallest, so it keeps re-reading the whole stack on each call.","workspacePanel":"trace","body":["getMin starts from the first value and checks each one, keeping the smallest it has seen."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class MinStack:\n    def __init__(self) -> None:\n        self.stack: list[int] = []\n\n    def push(self, val: int) -> None:\n        self.stack.append(val)\n\n    def pop(self) -> None:\n        self.stack.pop()\n\n    def top(self) -> int:\n        return self.stack[-1]\n\n    def getMin(self) -> int:\n        best: int = self.stack[0]\n        for x in self.stack:\n            if x < best:\n                best = x\n        return best","steps":[{"id":"seed-best","title":"Start from the bottom value","codeLine":15,"summary":"The stack holds -2, 0, -3. best starts at the bottom value, -2.","state":{"stack":[-2,0,-3],"stackActive":[0],"best":-2,"labels":{"stack":"stack"}}},{"id":"scan-middle","title":"Check the next value","codeLine":17,"summary":"0 is compared against best. 0 is not smaller than -2, so best stays -2.","state":{"stack":[-2,0,-3],"stackActive":[1],"best":-2,"labels":{"stack":"stack"}}},{"id":"scan-top","title":"Reach the top value","codeLine":18,"summary":"-3 is smaller than -2, so best becomes -3. Only after touching all three values is the answer known.","state":{"stack":[-2,0,-3],"stackActive":[2],"best":-3,"labels":{"stack":"stack"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class MinStack {\n    constructor() {\n        this.stack = [];\n    }\n\n    push(val) {\n        this.stack.push(val);\n    }\n\n    pop() {\n        this.stack.pop();\n    }\n\n    top() {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin() {\n        let best = this.stack[0];\n        for (const x of this.stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":3,"6":7,"9":11,"12":15,"15":19,"16":20,"17":21,"18":22,"19":25},"statementBundles":{"3":{"startLine":3,"endLine":6},"6":{"startLine":7,"endLine":10},"9":{"startLine":11,"endLine":14},"12":{"startLine":15,"endLine":18},"18":{"startLine":22,"endLine":24},"19":{"startLine":25,"endLine":27}},"alternateStyles":{"close-to-source":{"code":"class MinStack {\n    constructor() {\n        this.stack = [];\n    }\n\n    push(val) {\n        this.stack.push(val);\n    }\n\n    pop() {\n        const poppedValue = this.stack.pop();\n        if (poppedValue === undefined) throw new Error(\"IndexError\");\n    }\n\n    top() {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin() {\n        let best = this.stack[0];\n        for (const x of this.stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":3,"6":7,"9":11,"12":16,"15":20,"16":21,"17":22,"18":23,"19":26},"statementBundles":{"3":{"startLine":3,"endLine":6},"6":{"startLine":7,"endLine":10},"9":{"startLine":11,"endLine":15},"12":{"startLine":16,"endLine":19},"18":{"startLine":23,"endLine":25},"19":{"startLine":26,"endLine":28}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class MinStack {\n    stack: Array<number>;\n\n    constructor() {\n        this.stack = [];\n    }\n\n    push(val: number): void {\n        this.stack.push(val);\n    }\n\n    pop(): void {\n        this.stack.pop();\n    }\n\n    top(): number {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin(): number {\n        let best = this.stack[0];\n        for (const x of this.stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":5,"6":9,"9":13,"12":17,"15":21,"16":22,"17":23,"18":24,"19":27},"statementBundles":{"3":{"startLine":5,"endLine":8},"6":{"startLine":9,"endLine":12},"9":{"startLine":13,"endLine":16},"12":{"startLine":17,"endLine":20},"18":{"startLine":24,"endLine":26},"19":{"startLine":27,"endLine":29}},"alternateStyles":{"close-to-source":{"code":"class MinStack {\n    stack: Array<number>;\n\n    constructor() {\n        this.stack = [];\n    }\n\n    push(val: number): void {\n        this.stack.push(val);\n    }\n\n    pop(): void {\n        const poppedValue = this.stack.pop();\n        if (poppedValue === undefined) throw new Error(\"IndexError\");\n    }\n\n    top(): number {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin(): number {\n        let best = this.stack[0];\n        for (const x of this.stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":5,"6":9,"9":13,"12":18,"15":22,"16":23,"17":24,"18":25,"19":28},"statementBundles":{"3":{"startLine":5,"endLine":8},"6":{"startLine":9,"endLine":12},"9":{"startLine":13,"endLine":17},"12":{"startLine":18,"endLine":21},"18":{"startLine":25,"endLine":27},"19":{"startLine":28,"endLine":30}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class MinStack {\n    List<Integer> stack;\n\n    public MinStack() {\n        this.stack = new ArrayList<Integer>();\n    }\n\n    public void push(int val) {\n        this.stack.add(val);\n    }\n\n    public void pop() {\n        this.stack.remove(this.stack.size() - 1);\n    }\n\n    public int top() {\n        return this.stack.get(this.stack.size() - 1);\n    }\n\n    public int getMin() {\n        int best = this.stack.get(0);\n        for (Integer x : this.stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":5,"6":9,"9":13,"12":17,"15":21,"16":22,"17":23,"18":24,"19":27},"statementBundles":{"3":{"startLine":5,"endLine":8},"6":{"startLine":9,"endLine":12},"9":{"startLine":13,"endLine":16},"12":{"startLine":17,"endLine":20},"18":{"startLine":24,"endLine":26},"19":{"startLine":27,"endLine":29}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class MinStack\n{\n    public List<int> stack;\n\n    public MinStack()\n    {\n        this.stack = new List<int>();\n    }\n\n    public void Push(int val)\n    {\n        this.stack.Add(val);\n    }\n\n    public void Pop()\n    {\n        this.stack.RemoveAt(this.stack.Count - 1);\n    }\n\n    public int Top()\n    {\n        return this.stack[this.stack.Count - 1];\n        return 0;\n    }\n\n    public int GetMin()\n    {\n        int best = this.stack[0];\n        foreach (int x in this.stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n        return 0;\n    }\n}","lineMap":{"3":7,"6":12,"9":17,"12":22,"15":28,"16":29,"17":30,"18":31,"19":34},"statementBundles":{"3":{"startLine":7,"endLine":11},"6":{"startLine":12,"endLine":16},"9":{"startLine":17,"endLine":21},"12":{"startLine":22,"endLine":27},"18":{"startLine":31,"endLine":33},"19":{"startLine":34,"endLine":37}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct MinStack {\n    vector<int> stack;\n\n    MinStack() {\n        this->stack = vector<int>{};\n    }\n\n    void push(int val) {\n        this->stack.push_back(val);\n    }\n\n    void pop() {\n        this->stack.pop_back();\n    }\n\n    int top() {\n        return this->stack[this->stack.size() - 1];\n    }\n\n    int get_min() {\n        int best = this->stack[0];\n        for (int x : this->stack) {\n            if (x < best) {\n                best = x;\n            }\n        }\n        return best;\n    }\n};","lineMap":{"3":5,"6":9,"9":13,"12":17,"15":21,"16":22,"17":23,"18":24,"19":27},"statementBundles":{"3":{"startLine":5,"endLine":8},"6":{"startLine":9,"endLine":12},"9":{"startLine":13,"endLine":16},"12":{"startLine":17,"endLine":20},"18":{"startLine":24,"endLine":26},"19":{"startLine":27,"endLine":29}}}}}},{"id":"getmin-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the cost","title":"With a deep stack queried often, how much work does scanning add up to?","summary":"getMin can be called as often as push, and each call starts the search over.","workspacePanel":"trace","options":[{"id":"per-call-depth","label":"Each getMin touches every stored value, so its cost grows with the stack depth on every call","rationale":"The search reads all the values to be sure it found the smallest, and it forgets that work before the next call, so a deep stack queried many times repeats a full walk each time.","isCorrect":true},{"id":"constant","label":"A small fixed amount, since the smallest value rarely changes","rationale":"How often the minimum changes does not help: the scan still has to read every value to confirm which is smallest, so each call grows with depth.","isCorrect":false},{"id":"amortized-cheap","label":"Cheap overall, because the first scan can be reused","rationale":"Nothing is reused here. Each getMin throws away its result, so the next call rebuilds the same search from the bottom.","isCorrect":false}],"answer":"Each call walks the whole stack, so getMin's cost grows with depth and repeats on every query. With 30000 calls on a deep stack, that scanning is the cost the constant-time requirement rules out."},{"id":"what-to-carry","kind":"case-probe","chapter":"The idea","eyebrow":"Choose the memory","title":"What could a value remember so getMin never has to search?","summary":"Push -2, then 0. The smallest so far is -2, even though 0 is on top.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"carry-state","state":{"stack":[-2,0],"stackActive":[1],"labels":{"stack":"stack"}}}]},"options":[{"id":"min-so-far","label":"The smallest value at or below it, recorded as each value is pushed","rationale":"If every value stores the minimum of everything up to its depth, then the value on top always carries the current minimum, and getMin just reads it.","isCorrect":true},{"id":"just-value","label":"Nothing extra, since top already knows the newest value","rationale":"The newest value can differ from the smallest value. Here 0 is on top, while getMin should return -2 beneath it.","isCorrect":false},{"id":"global-min","label":"One shared minimum for the whole stack","rationale":"A single shared minimum cannot recover the previous minimum after the smallest value is popped, so it goes stale on the next pop.","isCorrect":false}],"answer":"Each value remembers the smallest value at or below its depth. With -2 then 0 pushed, that record is -2 then still -2, so the top of the record is the current minimum."},{"id":"where-to-keep-it","kind":"case-probe","chapter":"The idea","eyebrow":"Name the structure","title":"Where should those running minimums live so a pop stays simple?","summary":"For the stack -2, 0, -3, the running minimums are -2, -2, -3, one per value. A pop removes the newest value and must also drop the minimum recorded for that depth.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pair-state","state":{"stack":[-2,0,-3],"stackActive":[2],"labels":{"stack":"stack"}}}]},"options":[{"id":"second-stack","label":"In a second stack that grows and shrinks alongside the value stack","rationale":"One minimum record per pushed value, stored in its own stack, means a pop drops the top of both stacks together and the new tops still line up.","isCorrect":true},{"id":"single-variable","label":"In a single variable holding the running minimum","rationale":"One variable cannot restore the previous minimum after the smallest value is popped, because the earlier minimum was never kept.","isCorrect":false},{"id":"inside-value","label":"Sorted into the value stack itself","rationale":"Mixing minimums into the value stack breaks push and pop order, since top would no longer return the most recently pushed value.","isCorrect":false}],"answer":"In a second stack, one minimum record per value. The value stack holds -2, 0, -3 and the minimum stack holds -2, -2, -3, so their tops always line up and a pop discards both."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which design should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"stack":[-2,0,-3],"arrays":[{"name":"min stack","values":[-2,-2,-3]}],"labels":{"stack":"stack"}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Two stacks that move in lockstep","workspacePanel":"visualizer","body":["Keep two stacks the same depth. The value stack holds what was pushed; the minimum stack holds, at each depth, the smallest value at or below it.","Every push adds one record to each stack, and a pop drops the top of both. getMin reads the top of the minimum stack.","The stacks start empty. Push -2, then 0, then -3, then pop one value, and predict what each stack records and returns along the way."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"stack":[],"arrays":[{"name":"min stack","values":[]}],"labels":{"stack":"stack"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the two stacks","title":"Trace push -2, 0, -3, then a pop","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"push-zero","state":{"stack":[-2,0],"stackActive":[1],"arrays":[{"name":"min stack","values":[-2,-2],"i":1}],"labels":{"stack":"stack"}}},{"id":"push-neg-three","state":{"stack":[-2,0,-3],"stackActive":[2],"arrays":[{"name":"min stack","values":[-2,-2,-3],"i":2}],"labels":{"stack":"stack"}}},{"id":"pop-top","state":{"stack":[-2,0],"stackActive":[1],"arrays":[{"name":"min stack","values":[-2,-2],"i":1}],"labels":{"stack":"stack"}}}]},"beats":[{"id":"push-zero","title":"Pushing 0, which value decides the new minimum record?","summary":"The value stack holds -2, and 0 is pushed on top.","options":[{"id":"min-of-two","label":"The smaller of 0 and the previous minimum, so the record copies -2 rather than 0","rationale":"Each push records the smaller of the pushed value and the minimum already on top, so 0 above -2 records -2 again. That is why the two tops now differ: value top 0, minimum top -2.","isCorrect":true},{"id":"zero","label":"The pushed value 0, since the newest value is always the new record","rationale":"The minimum stack does not copy the pushed value; it copies the smaller of the value and the running minimum. 0 is larger than -2, so the record stays -2.","isCorrect":false},{"id":"nothing","label":"Neither, because the minimum only changes when a smaller value arrives","rationale":"Skipping the record would leave the two stacks at different depths, so the next pop would drop mismatched tops. Every push adds exactly one record.","isCorrect":false}],"answer":"The push compares 0 against the previous minimum -2 and records the smaller, -2. Because the record only copies, not searches, getMin stays a single read even though the smallest now sits below the top."},{"id":"push-neg-three","title":"Pushing -3, why do top and getMin now read the same value?","summary":"The stacks hold values -2, 0 and minimums -2, -2, and -3 is pushed next.","options":[{"id":"newest-is-smallest","label":"The newest value -3 is also the smallest so far, so its record copies -3 and the two tops coincide","rationale":"-3 is smaller than the previous minimum -2, so the record copies -3. The value top and the minimum top happen to agree here only because the newest push is also the new minimum.","isCorrect":true},{"id":"always-equal","label":"top and getMin always match, since both stacks store the same values","rationale":"They matched here by coincidence. One push earlier, value top was 0 while minimum top was -2, so the two stacks do not store the same values.","isCorrect":false},{"id":"min-unchanged","label":"getMin stays -2, because -3 does not change a minimum already recorded","rationale":"The push records the smaller of -3 and -2, which is -3, so the minimum top updates to -3 rather than staying -2.","isCorrect":false}],"answer":"They agree because the value just pushed, -3, is also the new smallest, so both tops are -3. One push earlier they disagreed, which is the normal case."},{"id":"pop-top","title":"After popping -3, how does getMin recover -2 without scanning?","summary":"The pop drops the top of both stacks together.","options":[{"id":"record-below-resurfaces","label":"Dropping the minimum top uncovers the record stored one depth down, which already held -2","rationale":"The minimum below -3 was recorded as -2 back when 0 was pushed, so removing the -3 record exposes it again. getMin reads that exposed top, no walk needed.","isCorrect":true},{"id":"recompute","label":"It re-scans the remaining values -2 and 0 to find the smallest","rationale":"No scan happens. The point of the paired stack is that the previous minimum was already recorded beneath, so it resurfaces the instant the top is dropped.","isCorrect":false},{"id":"stays-three","label":"It cannot, so getMin still reports the popped value -3","rationale":"Both tops are dropped on the same step, so the -3 record leaves with the value. The exposed minimum top is -2, the smallest of what remains.","isCorrect":false}],"answer":"Removing both tops uncovers the minimum recorded one depth down, which was already -2. The previous minimum was stored on the way up, so a pop restores it with a single read."}]},{"id":"pop-one-stack-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Can pop just remove from the value stack?","summary":"Leaving the minimum stack alone on a pop seems harmless: getMin still reads its top. It even looks right while the minimum never changes. Watch push 5, push 1, then a pop on a stack that forgets to shrink the minimum stack.","workspacePanel":"trace","pitfall":"The pop below removes a value from the value stack but never drops the matching entry from the minimum stack.","whyItMatters":"The two stacks have to stay the same depth, because the minimum stack top is the minimum of exactly the values still present. Popping only the value stack leaves a stale minimum record on top, so getMin reports a value that is no longer in the stack. Pop both stacks on the same step so their tops always line up.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class MinStack:\n    def __init__(self) -> None:\n        self.stack: list[int] = []\n        self.min_stack: list[int] = []\n\n    def push(self, val: int) -> None:\n        self.stack.append(val)\n        if len(self.min_stack) == 0 or val < self.min_stack[-1]:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(self.min_stack[-1])\n\n    def pop(self) -> None:\n        self.stack.pop()\n\n    def top(self) -> int:\n        return self.stack[-1]\n\n    def getMin(self) -> int:\n        return self.min_stack[-1]","steps":[{"id":"push-five","title":"Push 5 into both stacks","codeLine":9,"summary":"5 is the first value, so both stacks record 5. Their tops line up.","state":{"stack":[5],"stackActive":[0],"arrays":[{"name":"min stack","values":[5],"i":0}],"labels":{"stack":"stack"}}},{"id":"push-one","title":"Push 1, the new minimum","codeLine":11,"summary":"1 is smaller than 5, so the value stack holds 5, 1 and the minimum stack holds 5, 1. getMin would read 1.","state":{"stack":[5,1],"stackActive":[1],"arrays":[{"name":"min stack","values":[5,1],"i":1}],"labels":{"stack":"stack"}}},{"id":"pop-value-only","title":"Pop removes only the value 1","codeLine":14,"summary":"The 1 leaves the value stack, which now holds just 5. But the minimum stack still holds 5, 1, with 1 on top.","state":{"stack":[5],"stackActive":[0],"arrays":[{"name":"min stack","values":[5,1],"i":1}],"labels":{"stack":"stack"}}},{"id":"stale-min","title":"getMin returns a value that is gone","codeLine":20,"summary":"getMin reads the minimum stack top, 1, but 1 was already popped. The stack holds only 5, so the answer should be 5.","state":{"stack":[5],"stackActive":[0],"arrays":[{"name":"min stack","values":[5,1],"i":1}],"best":1,"labels":{"stack":"stack"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class MinStack {\n    constructor() {\n        this.stack = [];\n        this.minStack = [];\n    }\n\n    push(val) {\n        this.stack.push(val);\n        if (this.minStack.length === 0 || val < this.minStack[this.minStack.length - 1]) {\n            this.minStack.push(val);\n        } else {\n            this.minStack.push(this.minStack[this.minStack.length - 1]);\n        }\n    }\n\n    pop() {\n        this.stack.pop();\n    }\n\n    top() {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin() {\n        return this.minStack[this.minStack.length - 1];\n    }\n}","lineMap":{"3":3,"4":4,"7":8,"8":9,"9":10,"10":11,"11":12,"14":17,"17":21,"20":25},"statementBundles":{"4":{"startLine":4,"endLine":7},"11":{"startLine":12,"endLine":16},"14":{"startLine":17,"endLine":20},"17":{"startLine":21,"endLine":24},"20":{"startLine":25,"endLine":27}},"alternateStyles":{"close-to-source":{"code":"class MinStack {\n    constructor() {\n        this.stack = [];\n        this.minStack = [];\n    }\n\n    push(val) {\n        this.stack.push(val);\n        if (this.minStack.length === 0 || val < this.minStack[this.minStack.length - 1]) {\n            this.minStack.push(val);\n        } else {\n            this.minStack.push(this.minStack[this.minStack.length - 1]);\n        }\n    }\n\n    pop() {\n        const poppedValue = this.stack.pop();\n        if (poppedValue === undefined) throw new Error(\"IndexError\");\n    }\n\n    top() {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin() {\n        return this.minStack[this.minStack.length - 1];\n    }\n}","lineMap":{"3":3,"4":4,"7":8,"8":9,"9":10,"10":11,"11":12,"14":17,"17":22,"20":26},"statementBundles":{"4":{"startLine":4,"endLine":7},"11":{"startLine":12,"endLine":16},"14":{"startLine":17,"endLine":21},"17":{"startLine":22,"endLine":25},"20":{"startLine":26,"endLine":28}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class MinStack {\n    minStack: Array<number>;\n    stack: Array<number>;\n\n    constructor() {\n        this.stack = [];\n        this.minStack = [];\n    }\n\n    push(val: number): void {\n        this.stack.push(val);\n        if (this.minStack.length === 0 || val < this.minStack[this.minStack.length - 1]) {\n            this.minStack.push(val);\n        } else {\n            this.minStack.push(this.minStack[this.minStack.length - 1]);\n        }\n    }\n\n    pop(): void {\n        this.stack.pop();\n    }\n\n    top(): number {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin(): number {\n        return this.minStack[this.minStack.length - 1];\n    }\n}","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":13,"10":14,"11":15,"14":20,"17":24,"20":28},"statementBundles":{"4":{"startLine":7,"endLine":10},"11":{"startLine":15,"endLine":19},"14":{"startLine":20,"endLine":23},"17":{"startLine":24,"endLine":27},"20":{"startLine":28,"endLine":30}},"alternateStyles":{"close-to-source":{"code":"class MinStack {\n    minStack: Array<number>;\n    stack: Array<number>;\n\n    constructor() {\n        this.stack = [];\n        this.minStack = [];\n    }\n\n    push(val: number): void {\n        this.stack.push(val);\n        if (this.minStack.length === 0 || val < this.minStack[this.minStack.length - 1]) {\n            this.minStack.push(val);\n        } else {\n            this.minStack.push(this.minStack[this.minStack.length - 1]);\n        }\n    }\n\n    pop(): void {\n        const poppedValue = this.stack.pop();\n        if (poppedValue === undefined) throw new Error(\"IndexError\");\n    }\n\n    top(): number {\n        return this.stack[this.stack.length - 1];\n    }\n\n    getMin(): number {\n        return this.minStack[this.minStack.length - 1];\n    }\n}","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":13,"10":14,"11":15,"14":20,"17":25,"20":29},"statementBundles":{"4":{"startLine":7,"endLine":10},"11":{"startLine":15,"endLine":19},"14":{"startLine":20,"endLine":24},"17":{"startLine":25,"endLine":28},"20":{"startLine":29,"endLine":31}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class MinStack {\n    List<Integer> minStack;\n    List<Integer> stack;\n\n    public MinStack() {\n        this.stack = new ArrayList<Integer>();\n        this.minStack = new ArrayList<Integer>();\n    }\n\n    public void push(int val) {\n        this.stack.add(val);\n        if ((this.minStack.isEmpty() || val < this.minStack.get(this.minStack.size() - 1))) {\n            this.minStack.add(val);\n        } else {\n            this.minStack.add(this.minStack.get(this.minStack.size() - 1));\n        }\n    }\n\n    public void pop() {\n        this.stack.remove(this.stack.size() - 1);\n    }\n\n    public int top() {\n        return this.stack.get(this.stack.size() - 1);\n    }\n\n    public int getMin() {\n        return this.minStack.get(this.minStack.size() - 1);\n    }\n}","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":13,"10":14,"11":15,"14":20,"17":24,"20":28},"statementBundles":{"4":{"startLine":7,"endLine":10},"11":{"startLine":15,"endLine":19},"14":{"startLine":20,"endLine":23},"17":{"startLine":24,"endLine":27},"20":{"startLine":28,"endLine":30}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class MinStack\n{\n    public List<int> minStack;\n    public List<int> stack;\n\n    public MinStack()\n    {\n        this.stack = new List<int>();\n        this.minStack = new List<int>();\n    }\n\n    public void Push(int val)\n    {\n        this.stack.Add(val);\n        if (this.minStack.Count == 0 || val < this.minStack[this.minStack.Count - 1]) {\n            this.minStack.Add(val);\n        } else {\n            this.minStack.Add(this.minStack[this.minStack.Count - 1]);\n        }\n    }\n\n    public void Pop()\n    {\n        this.stack.RemoveAt(this.stack.Count - 1);\n    }\n\n    public int Top()\n    {\n        return this.stack[this.stack.Count - 1];\n        return 0;\n    }\n\n    public int GetMin()\n    {\n        return this.minStack[this.minStack.Count - 1];\n        return 0;\n    }\n}","lineMap":{"3":8,"4":9,"7":14,"8":15,"9":16,"10":17,"11":18,"14":24,"17":29,"20":35},"statementBundles":{"4":{"startLine":9,"endLine":13},"11":{"startLine":18,"endLine":23},"14":{"startLine":24,"endLine":28},"17":{"startLine":29,"endLine":34},"20":{"startLine":35,"endLine":38}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct MinStack {\n    vector<int> min_stack;\n    vector<int> stack;\n\n    MinStack() {\n        this->stack = vector<int>{};\n        this->min_stack = vector<int>{};\n    }\n\n    void push(int val) {\n        this->stack.push_back(val);\n        if ((this->min_stack.empty() || val < this->min_stack[this->min_stack.size() - 1])) {\n            this->min_stack.push_back(val);\n        } else {\n            this->min_stack.push_back(this->min_stack[this->min_stack.size() - 1]);\n        }\n    }\n\n    void pop() {\n        this->stack.pop_back();\n    }\n\n    int top() {\n        return this->stack[this->stack.size() - 1];\n    }\n\n    int get_min() {\n        return this->min_stack[this->min_stack.size() - 1];\n    }\n};","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":13,"10":14,"11":15,"14":20,"17":24,"20":28},"statementBundles":{"4":{"startLine":7,"endLine":10},"11":{"startLine":15,"endLine":19},"14":{"startLine":20,"endLine":23},"17":{"startLine":24,"endLine":27},"20":{"startLine":28,"endLine":30}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Pairing a minimum record with every value handled the mixed run cleanly. The cases that bite are the ones that stress how the records are built and torn down.","Two are worth a look before coding: the same minimum pushed twice, and a first push that has to seed both stacks from nothing."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"stack":[2,2],"arrays":[{"name":"min stack","values":[2,2]}],"labels":{"stack":"stack"}}}]}},{"id":"duplicate-min-probe","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"After push 2, push 2, pop, what does getMin return?","summary":"The minimum 2 has been pushed twice; one copy is now popped.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dup-state","state":{"stack":[2],"stackActive":[0],"arrays":[{"name":"min stack","values":[2],"i":0}],"labels":{"stack":"stack"}}}]},"options":[{"id":"still-two","label":"2, because the second copy left its own minimum record behind","rationale":"Each push of 2 added a record of 2, so the minimum stack held 2, 2. Popping one copy drops one record and the other 2 remains on top.","isCorrect":true},{"id":"nothing","label":"Nothing valid, the minimum was removed","rationale":"Only one 2 was popped. Because every push stored its own minimum, the second 2 still has a record keeping the minimum at 2.","isCorrect":false},{"id":"collapse","label":"It depends, since equal minimums share one record","rationale":"Sharing one record for equal minimums is the bug this avoids. One record per pushed value means the duplicate is tracked independently.","isCorrect":false}],"answer":"2. One record per pushed value means two 2s store two records, so popping one leaves the other, and getMin stays 2."},{"id":"single-value-probe","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"With just push(-10), what do top and getMin report?","summary":"Only one value has ever been pushed, so both stacks are one deep.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"stack":[-10],"stackActive":[0],"arrays":[{"name":"min stack","values":[-10],"i":0}],"labels":{"stack":"stack"}}}]},"options":[{"id":"both-ten","label":"Both return -10","rationale":"The first push has no previous minimum to compare against, so it stores the value itself in both stacks, and top and getMin read the same -10.","isCorrect":true},{"id":"top-only","label":"top is -10 but getMin has no answer yet","rationale":"The first push seeds the minimum stack too, so getMin has -10 to read. It is not left empty.","isCorrect":false},{"id":"zero","label":"top is -10 and getMin is 0","rationale":"There is no zero default; the minimum stack stored -10 on the first push, so getMin returns -10.","isCorrect":false}],"answer":"Both return -10. With no earlier minimum to compare, the first push records the value in both stacks, so top and getMin agree."},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Build the paired-stack design","summary":"One minimum record per push, and both tops dropped together on pop, is what keeps the two stacks aligned.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Start both stacks empty. On a push, store the value in the value stack and store the smaller of the new value and the current minimum in the minimum stack, so the two stay the same depth.","On a pop, drop the top of both stacks together. top reads the top of the value stack, and getMin reads the top of the minimum stack, each in constant time."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"stack":[],"arrays":[{"name":"min stack","values":[]}],"labels":{"stack":"stack"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the paired min stack","summary":"Now build the paired design: start both stacks empty, push the value onto the value stack, record the smaller of it and the current minimum onto the minimum stack, pop both tops together, then read top off the value stack and getMin off the minimum stack.","workspacePanel":"code","checkpoints":[{"id":"init-state","title":"Initialize the two stacks","description":"Create a value stack and a matching minimum stack in the constructor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"initializes_parallel_sequence_state","scope":"init-state","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Initialize parallel sequence-backed instance state.","doneWhen":"The constructor creates at least two empty sequence fields on the instance.","shouldFailWhen":"The class has only one stack or uses only local state.","roles":["value stack","minimum stack"],"mustProve":["parallel sequence state initialized"],"mustNotAccept":["single stack only"]},"hint":"Both stacks should start empty and have matching depths."},{"id":"push-value","title":"Push the value","description":"Append the new value to the main stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"pushes_primary_sequence_value","scope":"push-value","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Store the pushed value in the primary instance stack.","doneWhen":"The push method appends its input value to an instance sequence field.","shouldFailWhen":"The value is not persisted on the object.","roles":["push value","value stack"],"mustProve":["method parameter pushed to instance state"],"mustNotAccept":["discarding the pushed value"],"proofSnippets":[{"id":"py-push-value","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)"}]},"hint":"The ordinary stack still needs every pushed value."},{"id":"push-min","title":"Update the minimum stack","description":"Append the current minimum for this stack depth.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"pushes_derived_extremum_state","scope":"push-derived","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Push a derived minimum value into a parallel instance sequence.","doneWhen":"The push method appends the min of the new value and the previous minimum top.","shouldFailWhen":"The min state is updated only when the value decreases or is recomputed by scanning.","roles":["minimum stack","new value","previous minimum"],"mustProve":["derived extremum push"],"mustNotAccept":["missing duplicate-depth minimum entry"],"proofSnippets":[{"id":"py-push-min","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))"}]},"hint":"Store the minimum for the new depth every time you push."},{"id":"pop-both","title":"Pop both stacks","description":"Remove one entry from the value stack and the minimum stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"pops_parallel_sequence_state","scope":"pop-method","readMode":"object-design-value-query-v1"}]},"semanticSpec":{"intent":"Keep parallel stack depths synchronized on pop.","doneWhen":"The pop method removes from both instance sequence fields.","shouldFailWhen":"Only the value stack is popped or the min stack can become stale.","roles":["value stack","minimum stack"],"mustProve":["paired instance pops"],"mustNotAccept":["popping one stack only"],"proofSnippets":[{"id":"py-pop-both","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))\n\n    def pop(self):\n        self.stack.pop()\n        self.min_stack.pop()"}]},"hint":"The min stack has one entry per value stack entry."},{"id":"top-method","title":"Return the value stack top","description":"Return the most recently pushed value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"returns_primary_sequence_top","scope":"top-method","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Expose the top of the primary value stack.","doneWhen":"The top method returns the top entry from the primary pushed-value field.","shouldFailWhen":"The method returns the minimum stack top or another value.","roles":["value stack top"],"mustProve":["primary sequence top return"],"mustNotAccept":["returning current minimum"],"proofSnippets":[{"id":"py-top-method","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))\n\n    def pop(self):\n        self.stack.pop()\n        self.min_stack.pop()\n\n    def top(self):\n        return self.stack[-1]"}]},"hint":"top reads from the ordinary value stack."},{"id":"get-min-method","title":"Return the minimum stack top","description":"Return the current minimum in O(1).","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"object-design","fact":"returns_derived_extremum_top","scope":"extremum-method","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Expose the top of the derived minimum stack.","doneWhen":"getMin returns the top entry from the derived extremum field.","shouldFailWhen":"getMin scans the value stack or returns the latest value.","roles":["minimum stack top"],"mustProve":["derived extremum top return"],"mustNotAccept":["linear scan for minimum"],"proofSnippets":[{"id":"py-get-min-method","language":"python","code":"class MinStack:\n    def __init__(self):\n        self.stack = []\n        self.min_stack = []\n\n    def push(self, val):\n        self.stack.append(val)\n        if not self.min_stack:\n            self.min_stack.append(val)\n        else:\n            self.min_stack.append(min(val, self.min_stack[-1]))\n\n    def pop(self):\n        self.stack.pop()\n        self.min_stack.pop()\n\n    def top(self):\n        return self.stack[-1]\n\n    def getMin(self):\n        return self.min_stack[-1]"}]},"hint":"getMin reads from the minimum stack, not from the value stack."}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"A paired minimum stack turns getMin from a search into a single read.","body":["The minimum stack records, at every depth, the smallest value at or below it, so its top is always the current minimum and getMin is a constant-time read instead of a scan.","Both stacks move together: one record per push, both tops dropped per pop, so the minimum stack never goes stale."],"takeaways":[{"title":"getMin reads the carried minimum","body":"Because each push stores the running minimum beside its value, getMin reads the minimum stack top in O(1) rather than walking the stack in O(n)."},{"title":"Push records the smaller of two","body":"On push, the minimum stack stores the smaller of the new value and the previous minimum, which is why a duplicate minimum keeps its own record."},{"title":"Pop both, or it goes stale","body":"A pop drops the top of both stacks together, so the new minimum top is the minimum of exactly the values that remain, all in O(1) and O(n) space."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"timeComplexity":"O(1) per operation","spaceComplexity":"O(n)"}
