{
  "id": "stacks-queues/stack",
  "version": 1,
  "deterministic": true,
  "url": "/dsa/stacks-queues/stack",
  "topic": {
    "slug": "stacks-queues",
    "title": "Stacks & Queues"
  },
  "title": "Stack",
  "tagline": "Last in, first out. The undo button of data structures.",
  "vizKind": "stack",
  "complexity": {
    "time": {
      "best": "O(1) push",
      "average": "O(1) pop",
      "worst": "O(1) peek"
    },
    "space": "O(n)",
    "growth": "constant",
    "note": "Push, pop and peek all take the same time whether the stack holds 3 items or 3 million. Nothing has to shuffle, because nothing below the top ever moves."
  },
  "code": {
    "javascript": "class Stack {\n  constructor() { this.items = []; }\n  push(value) {\n    this.items.push(value);\n  }\n  pop() {\n    if (this.isEmpty()) return null;\n    return this.items.pop();\n  }\n  peek() {\n    return this.items[this.items.length - 1];\n  }\n  isEmpty() {\n    return this.items.length === 0;\n  }\n}",
    "python": "class Stack:\n    def __init__(self): self.items = []\n\n    def push(self, value):\n        self.items.append(value)\n\n    def pop(self):\n        if self.is_empty(): return None\n        return self.items.pop()\n\n    def peek(self):\n        return self.items[-1]\n\n    def is_empty(self):\n        return len(self.items) == 0\n",
    "java": "class Stack {\n  private List<Integer> items = new ArrayList<>();\n\n  void push(int value) {\n    items.add(value);\n  }\n  Integer pop() {\n    if (isEmpty()) return null;\n    return items.remove(items.size() - 1);\n  }\n  Integer peek() {\n    return items.get(items.size() - 1);\n  }\n  boolean isEmpty() {\n    return items.isEmpty();\n  }\n}",
    "cpp": "class Stack {\n  vector<int> items;\npublic:\n  void push(int value) {\n    items.push_back(value);\n  }\n  int pop() {\n    if (isEmpty()) return -1;\n    int top = items.back();\n    items.pop_back();\n    return top;\n  }\n  int peek() { return items.back(); }\n  bool isEmpty() {\n    return items.empty();\n  }\n};"
  },
  "defaultInput": [
    3,
    7,
    1,
    9
  ],
  "defaultTarget": null,
  "inputHint": "These get pushed one by one. Then we peek, and pop twice.",
  "pitfalls": [
    {
      "wrong": "Popping without checking whether the stack is empty.",
      "right": "Popping an empty stack is a classic crash. Always ask isEmpty() first, or make pop return null."
    },
    {
      "wrong": "Confusing peek with pop.",
      "right": "peek looks at the top and leaves it there. pop takes it away. Using pop when you meant peek quietly destroys your data."
    },
    {
      "wrong": "Trying to reach an item in the middle.",
      "right": "You can't — not without popping everything above it. If you need that, a stack is the wrong structure and you probably want an array."
    }
  ],
  "quiz": [
    {
      "q": "You push 1, 2, 3, then pop once. What comes out?",
      "options": [
        "1",
        "2",
        "3",
        "Nothing"
      ],
      "answer": 2,
      "why": "3 went on last, so 3 comes off first. Last in, first out."
    },
    {
      "q": "Why is 'stack overflow' called that?",
      "options": [
        "It's just a website name",
        "Function calls pile onto a stack, and infinite recursion fills it up",
        "The stack sorts itself and overflows",
        "It means you ran out of disk space"
      ],
      "answer": 1,
      "why": "Every function call is pushed onto the call stack. Recursion with no base case pushes forever, until the stack has no room left. It literally overflows."
    },
    {
      "q": "How long does it take to push onto a stack holding a million items?",
      "options": [
        "A million steps",
        "About 20 steps",
        "One step",
        "It depends on the values"
      ],
      "answer": 2,
      "why": "One. You only ever touch the top — the size of the pile beneath it is irrelevant. That's O(1)."
    }
  ],
  "problems": [
    {
      "name": "Valid Parentheses",
      "difficulty": "Easy",
      "url": "https://leetcode.com/problems/valid-parentheses/"
    },
    {
      "name": "Min Stack",
      "difficulty": "Medium",
      "url": "https://leetcode.com/problems/min-stack/"
    },
    {
      "name": "Evaluate Reverse Polish Notation",
      "difficulty": "Medium",
      "url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/"
    }
  ],
  "trace": {
    "note": "Each frame is one immutable step: data snapshot, pointers, per-index roles, executing code line, and a one-sentence explanation.",
    "length": 11,
    "frames": [
      {
        "data": {
          "items": []
        },
        "pointers": [],
        "highlights": [],
        "codeLine": 1,
        "variables": {
          "size": 0
        },
        "explanation": "A stack is a pile of plates. You add to the top, and you take from the top. The bottom plate is trapped until everything above it is gone.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 0
          }
        ],
        "highlights": [
          {
            "index": 0,
            "role": "swap"
          }
        ],
        "codeLine": 4,
        "variables": {
          "pushed": 3,
          "size": 1
        },
        "explanation": "push(3) — 3 goes on top of the pile.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 1
          }
        ],
        "highlights": [
          {
            "index": 1,
            "role": "swap"
          }
        ],
        "codeLine": 4,
        "variables": {
          "pushed": 7,
          "size": 2
        },
        "explanation": "push(7) — 7 goes on top of the pile.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            },
            {
              "id": "s2-1",
              "value": 1
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 2
          }
        ],
        "highlights": [
          {
            "index": 2,
            "role": "swap"
          }
        ],
        "codeLine": 4,
        "variables": {
          "pushed": 1,
          "size": 3
        },
        "explanation": "push(1) — 1 goes on top of the pile.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            },
            {
              "id": "s2-1",
              "value": 1
            },
            {
              "id": "s3-9",
              "value": 9
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 3
          }
        ],
        "highlights": [
          {
            "index": 3,
            "role": "swap"
          }
        ],
        "codeLine": 4,
        "variables": {
          "pushed": 9,
          "size": 4
        },
        "explanation": "push(9) — 9 goes on top of the pile.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            },
            {
              "id": "s2-1",
              "value": 1
            },
            {
              "id": "s3-9",
              "value": 9
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 3
          }
        ],
        "highlights": [
          {
            "index": 3,
            "role": "found"
          }
        ],
        "codeLine": 11,
        "variables": {
          "peeked": 9,
          "size": 4
        },
        "explanation": "peek() — look at the top plate (9) without taking it. The pile is unchanged.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            },
            {
              "id": "s2-1",
              "value": 1
            },
            {
              "id": "s3-9",
              "value": 9
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 3
          }
        ],
        "highlights": [
          {
            "index": 3,
            "role": "compare"
          }
        ],
        "codeLine": 7,
        "variables": {
          "popping": 9,
          "size": 4
        },
        "explanation": "pop() — the top plate is 9. That is the one that comes off.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            },
            {
              "id": "s2-1",
              "value": 1
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 2
          }
        ],
        "highlights": [
          {
            "index": 2,
            "role": "active"
          }
        ],
        "codeLine": 8,
        "variables": {
          "popped": 9,
          "size": 3
        },
        "explanation": "9 is gone. 1 is the new top — the last one that went in is the first one out.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            },
            {
              "id": "s2-1",
              "value": 1
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 2
          }
        ],
        "highlights": [
          {
            "index": 2,
            "role": "compare"
          }
        ],
        "codeLine": 7,
        "variables": {
          "popping": 1,
          "size": 3
        },
        "explanation": "pop() — the top plate is 1. That is the one that comes off.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            }
          ]
        },
        "pointers": [
          {
            "name": "top",
            "index": 1
          }
        ],
        "highlights": [
          {
            "index": 1,
            "role": "active"
          }
        ],
        "codeLine": 8,
        "variables": {
          "popped": 1,
          "size": 2
        },
        "explanation": "1 is gone. 7 is the new top — the last one that went in is the first one out.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      },
      {
        "data": {
          "items": [
            {
              "id": "s0-3",
              "value": 3
            },
            {
              "id": "s1-7",
              "value": 7
            }
          ]
        },
        "pointers": [],
        "highlights": [],
        "codeLine": 14,
        "variables": {
          "size": 2,
          "isEmpty": false
        },
        "explanation": "The stack holds 2 items. Every push and every pop touched only the top — which is why both are instant, no matter how tall the pile gets.",
        "stats": {
          "comparisons": 0,
          "swaps": 0
        }
      }
    ]
  }
}