Lesson 5.14 · Write it
The top of a small stack
A functionPython or Java14 tests, 9 of them hidden
On a phone? Put the lines in order instead
A cafe has a shelf with room for only a few trays, one on top of the other. Write a function that carries out a list of moves, in order, on a stack that starts empty and can hold at most capacity values, and returns the value on top after the last move.
- A move above 0 is pushed onto the stack, unless the stack already holds
capacityvalues. Then that move is refused, and the stack does not change. - A move of 0 pops the top value off the stack. A 0 when the stack is empty does nothing.
- Return the value on top of the stack after the last move, without taking it off. If the stack is empty at the end, return -1.
capacityis between 1 and 10. Every move is between 0 and 999. There are at most 50 moves, and the list of moves can be empty.
Only the number your function returns is checked.
def top_after(capacity: int, moves: list[int]) -> int
Examples
Your function is tested on 14 cases: the 5 examples below, and 9 hidden ones that check the rules above.
- top_after(3, [4, 9, 0, 6]) should return 6: the 0 takes off 9, and 6 is pushed last, so 6 is on top (rule 3)
- top_after(2, [5, 6, 7]) should return 6: the stack is full after 6, so 7 is refused (rule 1)
- top_after(3, [8, 0]) should return -1: the stack is empty at the end (rule 3)
- top_after(1, [0, 2]) should return 2: a 0 on an empty stack does nothing (rule 2)
- top_after(3, [9, 1, 9, 0]) should return 1: the pop takes the top 9, not the bottom one (rule 2)
public static int topAfter(int capacity, int[] moves)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 14 cases: the 5 examples below, and 9 hidden ones that check the rules above.
- topAfter(3, new int[]{4, 9, 0, 6}) should return 6: the 0 takes off 9, and 6 is pushed last, so 6 is on top (rule 3)
- topAfter(2, new int[]{5, 6, 7}) should return 6: the stack is full after 6, so 7 is refused (rule 1)
- topAfter(3, new int[]{8, 0}) should return -1: the stack is empty at the end (rule 3)
- topAfter(1, new int[]{0, 2}) should return 2: a 0 on an empty stack does nothing (rule 2)
- topAfter(3, new int[]{9, 1, 9, 0}) should return 1: the pop takes the top 9, not the bottom one (rule 2)