Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    DSADSA

    Foundations: measuring code

    • Big-O: how code grows
    • Space and the time–memory trade-off
    • Arrays and strings under the hood
    • Hash maps and sets
    • How to approach any interview problem

    Array patterns

    • Two pointers
    • Sliding window
    • Prefix sums
    • Binary search, done right
    • Sorting: merge sort and quicksort

    Stacks, queues and linked lists

    • Stacks and monotonic stacks
    • Queues and deques
    • Linked lists

    Recursion and trees

    • Recursion without fear
    • Backtracking: try and undo
    • Binary trees
    • Binary search trees
    • Heaps and priority queues

    Graphs and dynamic programming

    • Graphs: BFS and DFS
    • Shortest paths, topological sort and union-find
    • Dynamic programming: the idea
    • DP on grids and strings
    • Greedy: the best choice right now
    DSA

    Stacks, queues and linked lists · Lesson 11 of 23

    Stacks and monotonic stacks

    Last in, first out: brackets, undo, and "the next greater number".

    13 minutes2 games

    A stack is like a pile of plates: add on top (push), remove from the top (pop). The last thing in is the first out (LIFO). In JavaScript a plain array is a ready-made stack: push and pop are both O(1).

    Stacks are everywhere: the browser's Back button, undo, and the call stack that runs your functions.

    JavaScript
    // Balanced brackets: every closer must match the most recent unclosed opener
    function balanced(s) {
      const pairs = { ")": "(", "]": "[", "}": "{" }
      const stack = []
      for (const ch of s) {
        if ("([{".includes(ch)) stack.push(ch)
        else if (ch in pairs) {
          if (stack.pop() !== pairs[ch]) return false
        }
      }
      return stack.length === 0
    }
    
    console.log(balanced("{[()]}"), balanced("([)]"), balanced("(("))
    Step by step1 / 6
    1. ▶const stack = []
    2. 2stack.push("{")
    3. 3stack.push("[")
    4. 4stack.pop()
    5. 5stack.push("(")
    6. 6console.log(stack.join(""))

    Variables

    stack[]

    Output

    …

    Monotonic stack: "the next bigger number"

    A classic question: for each day, how many days until a warmer one? The simple solution is O(n²). The clever one: a stack of days still waiting for a warmer day, with temperatures decreasing from bottom to top. When a day warmer than the top arrives, it's that day's answer: pop it and repeat.

    JavaScript
    function warmerDays(temps) {
      const wait = new Array(temps.length).fill(0)
      const stack = []                       // indexes, temperatures decreasing
      for (let i = 0; i < temps.length; i++) {
        while (stack.length && temps[i] > temps[stack[stack.length - 1]]) {
          const day = stack.pop()
          wait[day] = i - day
        }
        stack.push(i)
      }
      return wait
    }
    
    console.log(warmerDays([30, 32, 31, 29, 33, 30]))

    Important

    Despite the while inside the for, a monotonic stack is O(n): each index is pushed once and popped at most once. Count complexity by what happens to each element, not by how many loops you see.

    What's the output?

    const stack = [1, 2, 3]
    stack.push(4)
    stack.pop()
    stack.pop()
    console.log(stack[stack.length - 1])

    What will this code print?

    Interview question

    How do you build a stack with an O(1) getMin()?

    Exercise

    Write evalPostfix(tokens) to evaluate a postfix expression (["2","1","+","3","*"] = (2+1)×3). Operators are + - * only. It must print 9 4.

    Expected output: 9 4

    JavaScript
    function evalPostfix(tokens) {
      
    }
    
    console.log(evalPostfix(["2", "1", "+", "3", "*"]), evalPostfix(["10", "2", "3", "*", "-"]))

    Practise on real problems

    Practice problems that use what you learned here. Solve them in JavaScript, Python or C++.

    • Balanced bracketsEasy
    • Postfix calculatorMedium
    • Days until a warmer dayMedium
    • Car fleetsMedium
    • Largest rectangle in a histogramHard

    Learn more from

    • Princeton Algorithms: Bags, Queues, and Stacksalgs4.cs.princeton.edu
    • Wikipedia: Stack (abstract data type)en.wikipedia.org
    • VisuAlgo: Linked List, Stack, Queuevisualgo.net

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    PreviousSorting: merge sort and quicksortNextQueues and deques
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.