Skip to content

Stack

storing

Level 1 of 3

Also called Last in, first out.

how it works

The idea in a few sentences and two pictures, then one run, moment by moment.

Think of a pile of plates. You put a number on the top, and you can take only the top one off. So the last one in is the first one out, LIFO for short. Its formal name is a stack, and a put and a take are usually called push and pop. A program keeps the pile in a row, its top at the end. A put writes after the last number, and a take removes the last. Each touches only the end, so each costs 1, however tall the pile, while the row has room. This page counts these puts and takes. The storyboard, the run drawn moment by moment below, puts on 3, 7 and 5, takes one, puts on 9, then takes two. The watch page counts each moment of a run as a step. A put is two moments, the number picked up, then set on, yet counts once among the puts and takes.

Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.

put 33put 737put 5375take375gives 5put 9379take379gives 9take37gives 7

Out, in turn: 5, 9, 7.

  • just put in
  • just taken out
The storyboard's seven operations, one a row. The red box was just put on; the dashed one just came off the top. 5, 9 and 7 come out, and 3 stays.

Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.

put 55put 252put 8528take528gives 8take52gives 2put 454take54gives 4take5gives 5

Out, in turn: 8, 2, 4, 5.

Queue, oldest out. Numbers join at the right end, the back, and leave from the left end, the front.

join 55join 252join 8528leave285gives 5leave82gives 2join 484leave48gives 8leave4gives 4

Out, in turn: 5, 2, 8, 4.

  • just put in
  • just taken out
The same eight operations, fed to a stack and to a queue, newest out and oldest out in Sebastian Bourges' books (volume two, chapter 21). They agree until the first take. Then the stack gives back the newest, 8, and the queue the oldest, 5. The queue's line steps forward, as its watch page draws it.
On and off: 8 moments of its 13 steps, the steps between them left for the watch page
  1. step 2 of 13

    3

    Pick up 3 to put it on the pile.

    what it remembers to know where it is
    doing operation
    1
    on top
    not yet
    in the pile
    0

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 3 of 13

    3

    Set 3 on the top. The pile now holds one number.

    what it remembers to know where it is
    doing operation
    1
    on top
    3
    in the pile
    1

    watch from here

  3. step 7 of 13

    375

    Set 5 on the top. The pile now holds 3 numbers.

    what it remembers to know where it is
    doing operation
    3
    on top
    5
    in the pile
    3

    watch from here

  4. step 8 of 13

    37

    Take the top number, 5, off the pile. 7 is now on top.

    what it remembers to know where it is
    doing operation
    4
    on top
    7
    in the pile
    2

    watch from here

  5. step 10 of 13

    379

    Set 9 on the top. The pile now holds 3 numbers.

    what it remembers to know where it is
    doing operation
    5
    on top
    9
    in the pile
    3

    watch from here

  6. step 11 of 13

    37

    Take the top number, 9, off the pile. 7 is now on top.

    what it remembers to know where it is
    doing operation
    6
    on top
    7
    in the pile
    2

    watch from here

  7. step 12 of 13

    3

    Take the top number, 7, off the pile. 3 is now on top.

    what it remembers to know where it is
    doing operation
    7
    on top
    3
    in the pile
    1

    watch from here

  8. step 13 of 13

    3

    Done. The pile holds one number.

    what it remembers to know where it is
    doing operation
    not yet
    on top
    3
    in the pile
    1

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. start with an empty pilePython line 7
  2. to put a number on, set it on the topPython lines 9 and 10
  3. to take one off, take the top numberPython lines 11 and 12
  4. an empty pile has nothing to takePython lines 11 and 13
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def stack(operations):
    """Run a list of operations on a pile kept in a row, its top at the end.

    A number puts it on the top, and None takes the top one off. Returns
    the pile that is left, bottom first. It never compares two numbers.
    """
    pile = []  # an empty pile
    for op in operations:
        if op is not None:  # put a number on
            pile.append(op)  # after the last number: the new top
        elif pile:  # take one off, if there is one
            pile.pop()  # the last number leaves, and comes back
        # an empty pile has nothing to take, so None does nothing
    return pile

how it scales

How the puts and takes grow, from ten numbers to a million, each number put on and then taken off.

Each step across or up is ten times the one before, a log-log plot. Smallest first, shuffled and biggest first all cost the same, 2n2n puts and takes, so the three cases draw one line. It climbs one step up for each step across: 20 puts and takes at 10 numbers, 2,000,000 at a million. Ten times the numbers, ten times the puts and takes.

puts and takes, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, n, ten times more at each mark to the right

  • put on biggest first, nn down to 1solid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
  • shuffled, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
  • put on smallest first, 1 to nnsolid where measured by running it; dashed where its formula carries it on to ten million
what a dearest row costs, at a billion puts and takes a second
nnputs and takestime
1,0002,000about 2 microseconds
100,000200,000about 200 microseconds
10,000,00020,000,000about 20 milliseconds

The puts and takes are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count a stack's puts and takes yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it puts n numbers on an
empty pile and takes them all off, and prints the puts and takes for 1 to
n in order, n down to 1, and the average over 20 shuffles of 1 to n. Each
put counts 1, and so does each take that gives a number back. The counts
are the same on any computer; only the time differs.
"""
import random


def stack(operations):
    """Run a list of operations on a pile kept in a row, its top at the end.

    A number puts it on the top, and None takes the top one off. Returns
    the pile that is left, bottom first. It never compares two numbers.
    """
    pile = []  # an empty pile
    for op in operations:
        if op is not None:  # put a number on
            pile.append(op)  # after the last number: the new top
        elif pile:  # take one off, if there is one
            pile.pop()  # the last number leaves, and comes back
        # an empty pile has nothing to take, so None does nothing
    return pile


def cheapest(n):
    """1 to n put on in order, then n takes."""
    return list(range(1, n + 1)) + [None] * n


def count(operations):
    """How many puts and takes the pile makes: each put, and each take that gives a number back."""
    puts = sum(1 for op in operations if op is not None)
    left = stack(operations)
    # every number put on is still on the pile, or came back once
    return puts + (puts - len(left))


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>8} {'in order':>10} {'n down to 1':>12} {'shuffled':>10}")
    for n in [10, 100, 1000, 10000, 100000]:
        row = list(range(1, n + 1))
        shuffles = []
        for _ in range(20):
            random.shuffle(row)
            shuffles.append(count(row + [None] * n))
        down = list(range(n, 0, -1)) + [None] * n
        print(f"{n:>8} {count(cheapest(n)):>10} {count(down):>12} {sum(shuffles) / 20:>10.1f}")

best, worst and average

Every order costs the same: nn puts and nn takes, 2n2n at every nn. No put or take looks at which number it holds, or compares two, so the order cannot change the count. At 4 numbers, 8 is 2 times 4. Each case is exactly 2 times nn, so its ceiling and its floor are that same multiple: Θ(n)\Theta(n), as lines 5 to 9 of section 4's first question show.

A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestput on smallest first, 1 to nnaverageshuffled, every order as likelyworstput on biggest first, nn down to 1
puts and takes2n2n2n2n, every order alike2n2n, no more than the rest
how the puts and takes grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n)\Theta(n)Θ(n)\Theta(n)
ceiling, OOO(n)O(n)O(n)O(n)O(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)Ω(n)\Omega(n)

extra memory: one place beside the row, where the top is (a row that doubles also keeps spare room, as section 4 draws it)

Extra memory is the room it needs on top of the input itself, while it runs.

order put onputstakesputs and takes
1, 2, 3, 4448
4, 3, 2, 1448
3, 1, 4, 2448
2, 4, 1, 3448
Four orders of 1 to 4, each put on, then all taken off. Each costs 8 puts and takes.

Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.

takeempty, nothing comesput 77put 373take73gives 3take7gives 7takeempty, nothing comes

Out, in turn: 3, 7.

  • just put in
  • just taken out
Six operations, but 4 puts and takes. The first and last takes find the pile empty: nothing comes back, and they are not counted.

where the formula comes from

Each count above, worked out line by line. Each reason names the line it uses, and each 'where does this come from?' box opens a fact from another page.

Why do nn numbers put on, then taken off, cost 2n2n puts and takes, biggest first or in any order?
  1. the move: count the puts

    the line:
    each put writes afterthe last number: counts 1\begin{gathered} \text{each put writes after} \\ \text{the last number: counts 1} \end{gathered}

    Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.

    put 44put 343put 2432put 14321take4321gives 1take432gives 2take43gives 3take4gives 4

    Out, in turn: 1, 2, 3, 4.

    • just put in
    • just taken out
    Biggest first. 4 puts, then 4 takes, each counting 1, 8 in all.

    why it is allowed: The concept page on what a structure promises counts a put so. A full row first copies its numbers, but those copies are counted apart, in the question on a growing row. nn puts count nn.

  2. the move: count the takes

    the line:
    each take removes the lastnumber: counts 1\begin{gathered} \text{each take removes the last} \\ \text{number: counts 1} \end{gathered}

    why it is allowed: The job takes off only as many as it put on, so every take finds a number and gives it back. nn takes count nn.

  3. the move: add them

    the line:
    W=n+nW = n + n

    why it is allowed: WW is the puts and takes of nn numbers put on, then taken off, biggest first. By lines 1 and 2. For 4, 4 + 4.

  4. the move: two lots of n

    the line:
    W=2nW = 2n

    why it is allowed: By line 3, nn and nn are two lots of nn. For 4, 8, as the picture counts.

  5. the move: a ceiling

    the line:
    W≤2nW \le 2n

    why it is allowed: By line 4. An equals gives a ceiling and a floor at once.

  6. the move: read it as a bound

    the line:
    W∈O(n)W \in O(n)

    why it is allowed: By line 5, with the fixed multiple 2.

  7. the move: a floor

    the line:
    W≥2nW \ge 2n

    why it is allowed: By line 4 again.

  8. the move: read it as a bound

    the line:
    W∈Ω(n)W \in \Omega(n)

    why it is allowed: By line 7, with the fixed multiple 2.

  9. the move: ceiling and floor together

    the line:
    W∈Θ(n)W \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound WW by the same growth, nn.

try it with a small nn: at n=4n = 4, line 3 gives W=8W = 8, which you can work out by hand

Why do numbers put on in order, smallest first, cost the same 2n2n puts and takes?
  1. the move: the order is never read

    the line:
    no put or take reads anumber, so in ordercosts the same\begin{gathered} \text{no put or take reads a} \\ \text{number, so in order} \\ \text{costs the same} \end{gathered}

    why it is allowed: Lines 1 and 2 of the first question count every put and every take as 1, whatever the numbers.

  2. the move: add them

    the line:
    B=n+nB = n + n

    why it is allowed: BB is the puts and takes on 1 to nn in order, put on, then taken off. By lines 1 and 2 of the first question, nn of each. For 4, 4 + 4.

  3. the move: two lots of n

    the line:
    B=2nB = 2n

    why it is allowed: The first question's formula, so its lines 5 to 9 give Θ(n)\Theta(n) here too.

try it with a small nn: at n=4n = 4, line 2 gives B=8B = 8, which you can work out by hand

Why do shuffled numbers cost 2n2n puts and takes on average?
  1. the move: every order costs the same

    the line:
    every order costs thesame puts and takes\begin{gathered} \text{every order costs the} \\ \text{same puts and takes} \end{gathered}

    why it is allowed: As in order, no put or take reads a number. The 6 orders of 1, 2 and 3 each cost 6.

  2. the move: average them

    the line:
    A=2nA = 2n

    why it is allowed: AA is the puts and takes over every order of nn numbers, each as likely. Equal costs average to that cost, 2n2n by line 4 of the first question, and its lines 5 to 9 give Θ(n)\Theta(n) here too. For 3, the 6 orders cost 36, and 36 shared by 6 is 6.

try it on small rows: over every order of 4 numbers, the average is A=8A = 8

A row with room for 1 doubles when a put finds it full. How many numbers do nn puts copy?
  1. the move: a full row doubles

    the line:
    room for 1, 2, 4, 8:each full row doubles\begin{gathered} \text{room for 1, 2, 4, 8:} \\ \text{each full row doubles} \end{gathered}
    copiedput 10put 21put 32put 40put 54put 60put 70put 80put 98Copies in all: 15.
    • held
    • just put in
    • copied into the new row, bracketed under it
    • room to spare
    Nine puts. The row doubles at puts 2, 3, 5 and 9, copying 1, 2, 4 and 8 numbers.

    why it is allowed: A put that finds the row full first copies every number into a new row with twice the room. Then it writes its own.

  2. the move: price a doubling

    the line:
    the put that finds the rowfull copies all it holds,its room: 1, 2, 4, and on\begin{gathered} \text{the put that finds the row} \\ \text{full copies all it holds,} \\ \text{its room: 1, 2, 4, and on} \end{gathered}
    full row6295new row629574 copied
    • held
    • copied into the new row, bracketed under it
    • just put in
    • room to spare
    Put 5 finds a row of 4 full. It copies each number to the same place in a row of 8, then writes 7.

    why it is allowed: The room starts at 1 and only doubles, so it runs 1, 2, 4, 8. A full row holds as many numbers as its room, and the next put copies them all. Put 5 finds 4 and copies 4.

  3. the move: the last room

    the line:
    the room after n puts is p,the smallest power of 2at or above n\begin{gathered} \text{the room after } n \text{ puts is } p \text{,} \\ \text{the smallest power of 2} \\ \text{at or above } n \end{gathered}
    × 21248169
    Doublings of 1 up to 16. 9 lies between 8 and 16, so pp is 16.

    why it is allowed: For 9, put 9 found the row full at 8 and doubled it to 16. So 8 is below 9, and 16 is at or above 9. In general, by line 2 the rooms run 1, 2, 4, and on, so pp is a power of 2. It holds all nn, so it is at least nn. It doubled from half of pp only when a put found that half full, so half of pp is below nn. This holds from 2 numbers on; at 1, nothing doubles.

  4. the move: add the copies

    the line:
    C=1+2+4+⋯+p2C = 1 + 2 + 4 + \dots + \frac{p}{2}

    why it is allowed: CC is the copies of nn puts. By lines 2 and 3, the doublings copy the rooms 1, 2, 4, and on, up to half of pp, the room before the last doubling. For 9, 1 + 2 + 4 + 8, and pp is 16.

  5. the move: add the doublings

    the line:
    C=p−1C = p - 1
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

      the line:
      S=1+2+4+⋯+2nS = 1 + 2 + 4 + \dots + 2^n

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Take SS from both sides of line 2. On the right, write SS out as line 1 does.

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Two lots of SS less one lot is one lot.

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    why it is allowed: The box under this line shows a doubling sum from 1 is one less than the next doubling. In the box, nn is not the puts: it counts the doublings from 1 to the last term. For 9 puts it is 3, as 1 doubled 3 times is 8, half of pp. After half of pp comes pp. For 9, 15 is 16 less 1.

  6. the move: the room is under twice the numbers

    the line:
    p<2np < 2n

    why it is allowed: By line 3, half of pp is below nn. Doubling both, pp is below 2n2n. For 9, 8 is below 9, so 16 is below 18.

  7. the move: a ceiling

    the line:
    C≤2n−1C \le 2n - 1

    why it is allowed: By lines 5 and 6, CC is pp less 1, and pp is below 2n2n, so CC is at most 2n−12n - 1. For 9, 15 is at most 17. That is under 2 copies a number; in Sebastian Bourges' books, 'Under two moves per item' (volume two, chapter 21; their moves are this page's copies).

  8. the move: add the puts' own writes

    the line:
    C+n≤3n−1C + n \le 3n - 1

    why it is allowed: Each put also writes its own number, nn writes in all. Add nn to both sides; 2n−12n - 1 and nn make 3n−13n - 1. For 9, 15 + 9 is 24, at most 26.

  9. the move: read it as a bound

    the line:
    C+n∈O(n)C + n \in O(n)

    why it is allowed: By line 8, with the fixed multiple 3.

  10. the move: share it out

    the line:
    C+nn≤3−1n\frac{C + n}{n} \le 3 - \frac{1}{n}
    putcopies and its writeso farshare so far
    1111
    2231.5
    3362
    4171.75
    55122.4
    6113about 2.17
    71142
    8115about 1.88
    9924about 2.67
    Each put's copies and its own write, added up as the puts come. The share never reaches 3.

    why it is allowed: Line 8 divided by nn shares the copies and writes over the nn puts. One put may copy many, as put 9 copies 8. For 9, 24 over 9.

  11. the move: under 3

    the line:
    C+nn<3\frac{C + n}{n} < 3

    why it is allowed: Line 10 takes one over nn from 3, and one over nn is above 0, so the share is under 3. For 9, 24 over 9 is about 2.67.

try it with a small nn: at n=9n = 9, line 4 gives C=15C = 15, which you can work out by hand

Keep the top at the row's start instead. How many moves do nn puts, then nn takes, make?
  1. the move: a put at the start

    the line:
    a put onto k numbersmoves each one place along\begin{gathered} \text{a put onto } k \text{ numbers} \\ \text{moves each one place along} \end{gathered}

    Stack, top at the start: place 1, on the left. A put moves each number held one place along; a take moves each one back.

    movesput 440put 8841put 33842take843gives 32take48gives 81take4gives 40

    Moves in all: 6.

    • just put in
    • just taken out
    • moved one place along
    • moved one place back
    Three numbers on, then off, with the top at place 1, on the left. Kept at the end, the same pile needs no moves.

    why it is allowed: The top is now place 1, so the new number needs place 1 free. Each of the kk numbers held moves one place along first.

  2. the move: a take at the start

    the line:
    a take leaving k numbersmoves each one place back\begin{gathered} \text{a take leaving } k \text{ numbers} \\ \text{moves each one place back} \end{gathered}

    why it is allowed: The top leaves place 1, and each of the kk numbers still held moves one place back to fill the gap.

  3. the move: add the moves

    the line:
    M=(0+1+⋯+(n−1))×2M = \bigl(0 + 1 + \dots + (n - 1)\bigr) \times 2

    why it is allowed: MM is the moves of nn puts, then nn takes. By line 1 the puts move 0, 1, up to n−1n - 1. By line 2 the takes move n−1n - 1, down to 0, the same sum. For 3, 6.

  4. the move: leave out the 0

    the line:
    M=(1+2+⋯+(n−1))×2M = \bigl(1 + 2 + \dots + (n - 1)\bigr) \times 2

    why it is allowed: Adding 0 changes nothing.

  5. the move: use the page on adding up

    the line:
    M=(n−1)((n−1)+1)2×2M = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2} \times 2
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: The box under this line adds 1 up to a last number with two staircases, that number times one more, halved. Here the last number is n−1n - 1. For 3, 2 times 3, halved, is 3, and times 2 is 6, as line 3.

  6. the move: halve, then double

    the line:
    M=(n−1)((n−1)+1)M = (n - 1)\bigl((n - 1) + 1\bigr)

    why it is allowed: Halving, then doubling, changes nothing. For 3, 3 doubled is 6.

  7. the move: tidy

    the line:
    M=(n−1)nM = (n - 1)n

    why it is allowed: (n−1)+1(n - 1) + 1 is nn. For 3, 2 times 3 is 6.

  8. the move: multiply out

    the line:
    M=n2−nM = n^2 - n

    why it is allowed: nn lots of nn, less nn lots of 1. For 3, 9 less 3.

  9. the move: add the puts and takes

    the line:
    M+2n=n2+nM + 2n = n^2 + n

    why it is allowed: Each put still writes its number and each take gives one back, 2n2n puts and takes, as with the top at the end. Add 2n2n to both sides; n2−nn^2 - n and 2n2n make n2+nn^2 + n. For 3, 6 + 6 is 12.

  10. the move: a ceiling

    the line:
    M≤n2M \le n^2

    why it is allowed: Line 8 takes nn away from n2n^2. For 3, 6 is at most 9.

  11. the move: read it as a bound

    the line:
    M∈O(n2)M \in O(n^2)

    why it is allowed: By line 10, with the fixed multiple 1.

  12. the move: a fact about n

    the line:
    n≤n22 for n≥2n \le \frac{n^2}{2} \text{ for } n \ge 2

    why it is allowed: n22\frac{n^2}{2} is nn times half of nn, and half of nn is at least 1 from 2 on. For 3, 3 is at most 4.5.

  13. the move: a floor

    the line:
    M≥n22 for n≥2M \ge \frac{n^2}{2} \text{ for } n \ge 2

    why it is allowed: Line 8 takes nn from n2n^2. By line 12, nn is at most half of n2n^2, so at least half is left. For 3, 9 less 3 is 6, at least 4.5.

  14. the move: read it as a bound

    the line:
    M∈Ω(n2)M \in \Omega(n^2)

    why it is allowed: By line 13, with the fixed multiple one half, from 2 numbers on.

  15. the move: ceiling and floor together

    the line:
    M∈Θ(n2)M \in \Theta(n^2)

    why it is allowed: Lines 11 and 14 bound MM by the same growth, n2n^2.

try it with a small nn: at n=3n = 3, line 3 gives M=6M = 6, which you can work out by hand

count it yourself

Count every put and take as 9, 6, 5 and 2 go on, biggest first, then all four come off. Each dash in the input is a take.

9, 6, 5, 2, -, -, -, -, every step written down
stepthe rowwhat happensput ontaken offputs and takes
1Start with an empty pile, and 8 operations to do.000
2Pick up 9 to put it on the pile.000
39Set 9 on the top. The pile now holds one number.9101
49Pick up 6 to put it on the pile.9101
59, 6Set 6 on the top. The pile now holds 2 numbers.9, 6202
69, 6Pick up 5 to put it on the pile.9, 6202
79, 6, 5Set 5 on the top. The pile now holds 3 numbers.9, 6, 5303
89, 6, 5Pick up 2 to put it on the pile.9, 6, 5303
99, 6, 5, 2Set 2 on the top. The pile now holds 4 numbers.9, 6, 5, 2404
109, 6, 5Take the top number, 2, off the pile. 5 is now on top.9, 6, 5415
119, 6Take the top number, 5, off the pile. 6 is now on top.9, 6426
129Take the top number, 6, off the pile. 9 is now on top.9437
13Take the top number, 9, off the pile. The pile is empty again.448
14Done. The pile holds nothing.448

In all, 8 puts and takes. The formula from section 4, 2n2n, gives W=8W = 8 at n=4n = 4: the same.

where you meet it

Piles are everywhere in programs, often without the name.

  • Python's list as a pile

    Python's list, its row of items, makes a pile: append puts on the end, and pop takes the end off and gives it back. The first table below asks a list called pile, one line at a time. On an empty list, pop stops with an error, IndexError, where this page's Python does nothing. CPython, the usual Python, gives a growing list room for 4, then 8, 16, 24 and 32. It doubles at first; a long list grows by about an eighth and a few places, so it grows more often than a doubling row.

    source: the Python tutorial, Using Lists as Stacks (opens in a new tab); CPython's Objects/listobject.c, list_resize

  • the call stack

    A function is a named piece of a program. When one starts another, a call, the program sets a frame on a pile: the call's own numbers and where to come back to. When the call ends, a return, its frame comes off. Python stops a pile of calls grown too tall: past 1,000 frames, unless you change the limit, it stops with an error called RecursionError.

    source: Python's documentation, sys.getrecursionlimit (opens in a new tab) and RecursionError (opens in a new tab); CPython's Include/internal/pycore_ceval.h, Py_DEFAULT_RECURSION_LIMIT

  • brackets and undo

    Sebastian Bourges' books check that brackets nest with a pile. Each opening bracket goes on, and each closing one must match the top and take it off. The second table below traces it. Undo works the same way: the last change made is the first one undone.

    source: Sebastian Bourges, Algorithmic Thinking Without the Jargon, volume two, chapter 21, 'Stacks and queues'

askedanswerthe list after
pile.append(4)None[4]
pile.append(7)None[4, 7]
pile.pop()7[4]
pile.pop()4[]
pile.pop()IndexError[]
stack([4, 7, None, None, None])[]this page's Python on 4, 7, -, -, -: the last take does nothing
A Python list called pile, empty at first, asked one line at a time. The third pop finds it empty. None is Python's word for no answer; this page's Python also uses it to mean a take.
readpile afterwhy
((opens, so goes on
[( [opens, so goes on
](closes the top, so it comes off
(( (opens, so goes on
)(closes the top, so it comes off
)emptycloses the top, so it comes off
the endemptynothing left open: they nest
The books' check, read left to right, each pile written bottom first, its top on the right. On ( ], it stops at ], which does not match the top, (.

what is used instead

When you must find a number inside, a pile is the wrong choice: it answers only which comes next. In the books' words, 'Do not reach for either when you also need to search' (volume two, chapter 21), either being a stack or a queue. When the oldest must come first, as at a printer, use a queue.

how it compares

Three ways to keep a pile, side by side. Each puts nn numbers on, then takes them all off.

waya puta takeall on then all offextra memoryreach for it when
top at the row's endcounts 1; a full row first copies every numbercounts 12n2n puts and takes, and at most 2n−12n - 1 copies if the row doublesspare room, if the row doublesalmost always
top at the row's startmoves each number held along, then counts 1counts 1, then moves each number still held backn2+nn^2 + n puts, takes and movesspare room, if the row doublesnever; the end makes the same puts and takes and no moves
a chain of placescounts 1counts 12n2n puts and takes, no copiesa link beside each numbera put must never wait for a copy
A move shifts a number one place. The chain links each number to the one below and works at its head, the top: a put is two link writes in Sebastian Bourges' books (volume two, chapter 21). It never copies, but each link takes memory.
102104106108101010121014101102103104105106107101102103104105106107108109101010111012101310141015101102103104105106107
  • top at the end, 2n2n
  • top at the start, n2+nn^2 + n
All on, then all off, on a log-log plot. The end climbs one step up for each step across; the start climbs about two. At a million numbers, 2 million puts and takes against about a million million puts, takes and moves.