DSA
    beginner

    Stack Data Structure

    Software Engineer path · lesson 4 of 99
    O(1) ops

    Syntax: push n · pop · peek. Numbers from -99 to 99.

    Try:
    stack →0
    PushedAbout to popPeekedOverflow

    Empty stack (capacity 8).

    Code (running line highlighted)
    1. 1push(x): items.append(x) # top is the end
    2. 2pop(): if empty: underflow; return items.pop()
    3. 3peek(): return items[-1] # look, don’t remove
    Pushes
    0 / 3
    Pops
    0 / 2
    Invariant: Last in, first out: only the top is ever touched.

    Tap any element in the diagram to inspect its state at this step.

    1 / 10

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Last in, first out

    Sequence

    Run push 1, push 2, push 3, pop, push 4, pop, pop, pop. Order the values as they are popped.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    4 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Which element is removed first in a Stack?

    Write the code

    Runs your solution

    Valid Parentheses

    Determine if an input string containing "()[]{}" is valid. Open brackets must be closed by the same type and in correct order.

    Example Cases

    Input:["()"]
    Output:true
    Input:["()[]{}"]
    Output:true
    Input:["(]"]
    Output:false
    Input:["([)]"]
    Output:false
    javascript
    function isValid(s) {
      // Your code here
    }

    The short version

    Think of a stack of plates in a cafeteria. You can only add a new plate to the top, and you can only take the top plate off. The last one put on is the first one taken off (LIFO).

    In more depth

    Last In, First Out (LIFO)

    Think of a stack of plates. You put a new plate on top, and you take the top plate off. You can't reach the bottom plate without removing all the ones above it.

    This simple LIFO property makes Stacks essential for:

    1.Function Calls (Recursion): Your computer uses a stack to remember where to return after a function finishes.
    2.Undo/Redo: Ctrl+Z pops the last action from the stack.
    3.Parsing: Checking if parentheses are balanced.

    When to reach for this

    • Processing nested structures (Parentheses, HTML tags)
    • Reversing data (String reverse, number base conversion)
    • Undo/Redo functionality
    • Expression evaluation (Calculator)

    Interview Questions

    Google
    Microsoft
    Bloomberg
    Amazon
    Uber
    Facebook
    Apple
    LinkedIn
    Microsoft
    Google
    Amazon
    DoorDash

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required