Stacks and Queues Building stacks and queues
186. Implement a Stack with an Array
Build a stack of integers on top of a plain array. The stack has a fixed capacity: it can never hold more
than capacity values. Write a class ArrayStack with a constructor and four methods:
ArrayStack(capacity)creates an empty stack that can hold at mostcapacityvalues.push(val)putsvalon top of the stack. If the stack already holdscapacityvalues, the stack is full, sopushdoes nothing andvalis dropped.pop()removes the value on top and returns it. If the stack is empty, it returns-1and changes nothing.top()returns the value on top without removing it, or-1if the stack is empty.size()returns how many values the stack holds.
Store the values in an array of length capacity, created once in the constructor. Do not use a built-in
stack, or a list that grows on its own. Each method must run in O(1) time.
Your class is tested by replaying a list of calls on a new ArrayStack(capacity). ops[i] names the i-th
call: "push", "pop", "top" or "size". The pushes take their values from values in order, so the
first push pushes values[0], the second pushes values[1], and so on, even when a push is dropped. The
answer is the list of every value that pop, top and size return, in the order they are called.
In C# and Go the methods are Push, Pop, Top and Size. Go creates the stack with
Constructor(capacity), and Rust with ArrayStack::new(capacity). The names in ops are the same in every
language.
Example 1
Input: capacity = 3
ops = ["push",
"push",
"push",
"push",
"top",
"pop",
"pop",
"size"]
values = [7, 2, 9, 4]
[9,9,2,1]Explanation: The first three pushes fill the stack with 7, 2 and 9 from the bottom up. The fourth push finds it full,
so 4 is dropped. top and the first pop both give 9, the second pop gives 2, and only 7 is left.
Example 2
Input: capacity = 2
ops = ["pop",
"top",
"push",
"top",
"pop",
"pop",
"size"]
values = [0]
[-1,-1,0,0,-1,0]Explanation: pop and top on the empty stack both return -1. After 0 is pushed, top and pop return 0, which is a
real value. The stack is then empty again, so the last pop returns -1.
Example 3
Input: capacity = 1
ops = ["push",
"push",
"size",
"pop",
"push",
"top"]
values = [1000000000, 1, 1000000000]
[1,1000000000,1000000000]Explanation: With room for one value, the push of 1 is dropped and size stays 1. After the pop empties the stack,
the next push has room again.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ capacity ≤ 1051 ≤ ops.length ≤ 105- Each
ops[i]is"push","pop","top"or"size". values.lengthequals the number of"push"calls inops.0 ≤ values[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.