Boss lesson · Unit 01
Evaluate and track
A postfix calculator and a stack that knows its minimum
What you practise
- Reverse Polish evaluation
- A stack that knows its minimum in O(1)
Try a question from this lesson
Pick one
In postfix notation the operator comes after its two numbers, so 3 4 + means 3 + 4. What is 2 3 4 * +?
Correct answer
14
Why
* applies to the two values just before it, 3 and 4, giving 12. Then + applies to 2 and 12. Reading it as (2 + 3) * 4 = 20 is the tempting mistake. Postfix needs no brackets and no precedence rules.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Numbers wait on a stack
To evaluate postfix, read the tokens left to right.
A number: push it. An operator: pop two numbers, apply the operator, and push the result back.
When the tokens run out, a valid expression has left exactly one value on the stack. That value is the answer.
Concept
A stack that knows its minimum
New problem: support push, pop and "what is the smallest item?", all in O(1). Scanning the stack for the minimum would be O(n).
The trick: push pairs. Beside each value, store the minimum of everything at or below it. The current minimum is then always in the top pair, and a pop removes a value together with the note about it.
stack = [] # (value, minimum)
stack.append((5, 5))
stack.append((3, 3)) # 3 is a new minimum
stack.append((7, 3)) # 7 is not
print(stack[-1][1]) # 3
stack.pop()
stack.pop()
print(stack[-1][1]) # 5const stack = []; // [value, minimum]
stack.push([5, 5]);
stack.push([3, 3]); // 3 is a new minimum
stack.push([7, 3]); // 7 is not
console.log(stack.at(-1)[1]); // 3
stack.pop();
stack.pop();
console.log(stack.at(-1)[1]); // 5type Entry = [number, number];
const stack: Entry[] = []; // [value, min]
stack.push([5, 5]);
stack.push([3, 3]); // 3 is a new minimum
stack.push([7, 3]); // 7 is not
console.log(stack.at(-1)![1]); // 3
stack.pop();
stack.pop();
console.log(stack.at(-1)![1]); // 5Python noteA tuple (value, low) is the natural pair in Python: small, fixed and immutable.
TypeScript note[number, number] is a tuple type: an array of exactly two numbers. Here it means value first, minimum second.
10 more exercises in the app
- 3× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
- 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.