Bitpath

Lesson 1 · Unit 01

Last in, first out

Push, pop and peek at the end of an array

11 exercisesabout 3 min

What you practise

  • Push, pop, peek on the end of an array, all O(1)

Try a question from this lesson

Pick one

You stack three plates: red, then green, then blue. You take two plates off the top. Which plate is left?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A stack is an array you only touch at the end

A stack has three moves. Push adds an item on top. Pop removes the top item and hands it to you. Peek reads the top item and leaves it there.

Use the end of an array as the top. Nothing ever shifts, so all three moves are O(1).

stack = []
stack.append(3)    # push
stack.append(7)    # push
top = stack[-1]    # peek: 7
stack.pop()        # pop: drops 7
print(top, len(stack))
const stack = [];
stack.push(3);            // push
stack.push(7);            // push
const top = stack.at(-1); // peek: 7
stack.pop();              // pop: drops 7
console.log(top, stack.length);
const stack: number[] = [];
stack.push(3);            // push
stack.push(7);            // push
const top = stack.at(-1); // peek: 7
stack.pop();              // pop: drops 7
console.log(top, stack.length);

Python noteA plain list is the stack: append pushes, pop() pops, stack[-1] peeks.

TypeScript noteconst stack: number[] = [] needs its annotation: an empty [] gives TypeScript nothing to infer the item type from.

9 more exercises in the app

  • 3× type the answer
  • 2× multiple choice
  • 1× true or false
  • 1× fill the blanks
  • 1× match the pairs
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy