arr[++top] = val and minArr[top] = min(minArr[top-1], val) — the first pushes the value, the second records the running minimum.push(v): check full, then arr[++top]=v, minArr[top]=min(minArr[top-1],v)pop(): check empty, then clear both arrays at top and top--peek(): read arr[top], change nothinggetMin(): read minArr[top] → O(1)minArr[i] holds the minimum of arr[0..i].min(oldMin, v) is the new prefix minimum;minArr[top-1] is already the minimum of what remains — nothing to recompute.Stack Overflow!; pop on empty → Stack Underflow!; peek / getMin on empty → Stack is empty!.top must start at -1 (not 0), otherwise the first element is off by one; (2) popping must clear both arrays, or a later push reusing that slot reads a stale minimum; (3) the first element has no previous minArr entry — handle it separately (the code here uses top==0 ? val : ...).| step | pushed | array[] | minarr[] | top | why |
|---|---|---|---|---|---|
| ① | 3 | (3) | (3) | 0 | first element: minarr[0] = 3 |
| ② | 2 | (3, 2) | (3, 2) | 1 | 2 < 3 → minarr[1] = 2 |
| ③ | 5 | (3, 2, 5) | (3, 2, 2) | 2 | 5 > 2 → minarr[2] = 2 (keep the previous minimum) |
| ④ | 1 | (3, 2, 5, 1) | (3, 2, 2, 1) | 3 | 1 < 2 → minarr[3] = 1 |
Rule: minarr[top] = min(minarr[top-1], array[top]); top is an index — it is -1 when empty and 0 after the first push (exactly step ①). getMin reads minarr[top] only; both arrays retreat together on pop, so nothing is recomputed.