Skip to content
ExamSpine

Lesson 5.14 · Write it

What is left on the stack

A functionPython or Java13 tests, 8 of them hidden

On a phone? Put the lines in order instead

A robot stacks numbered boxes in a warehouse. It is given a list of moves, and it carries them out in order on a stack that starts empty. Write a function that returns what the stack holds after the last move.

  1. A move above 0 is a box number: push it onto the stack.
  2. A move of 0 means pop: take the top box off the stack. A 0 when the stack is empty does nothing.
  3. Return the box numbers still on the stack as a list, bottom first, so the top is the last value. An empty stack is an empty list. In Java, return an ArrayList<Integer>.
  4. Every move is between 0 and 999. There are at most 50 moves, and the list of moves can be empty.

Only the list your function returns is checked.

def stack_after(moves: list[int]) -> list[int]

Examples

Your function is tested on 13 cases: the 5 examples below, and 8 hidden ones that check the rules above.

  • stack_after([4, 9, 0, 6]) should return [4, 6]: the 0 takes off 9, the box pushed last (rule 2)
  • stack_after([0, 3]) should return [3]: a 0 on an empty stack does nothing (rule 2)
  • stack_after([1, 2, 3]) should return [1, 2, 3]: no pops: the list is bottom first, in the order the boxes went on (rule 3)
  • stack_after([5, 0]) should return []: the only box comes off, so the stack is empty (rule 3)
  • stack_after([9, 1, 9, 0]) should return [9, 1]: the top 9 comes off, not the 9 at the bottom (rule 2)

public static ArrayList<Integer> stackAfter(int[] moves)

Checking whether Java answers can run here.

Examples

Your function is tested on 13 cases: the 5 examples below, and 8 hidden ones that check the rules above.

  • stackAfter(new int[]{4, 9, 0, 6}) should return [4, 6]: the 0 takes off 9, the box pushed last (rule 2)
  • stackAfter(new int[]{0, 3}) should return [3]: a 0 on an empty stack does nothing (rule 2)
  • stackAfter(new int[]{1, 2, 3}) should return [1, 2, 3]: no pops: the list is bottom first, in the order the boxes went on (rule 3)
  • stackAfter(new int[]{5, 0}) should return []: the only box comes off, so the stack is empty (rule 3)
  • stackAfter(new int[]{9, 1, 9, 0}) should return [9, 1]: the top 9 comes off, not the 9 at the bottom (rule 2)
solution.pySolution.java