Stacks and Queues Building stacks and queues
187. Implement a Queue with an Array
A queue hands values back in the order they went in: the value that has waited longest leaves first. Build a
queue of integers on a plain array. Write a class ArrayQueue with a constructor and four methods:
ArrayQueue(capacity)creates an empty queue that can hold at mostcapacityvalues.enqueue(value)addsvalueat the back of the queue. If the queue already holdscapacityvalues, it does nothing, andvalueis dropped.dequeue()removes the value at the front of the queue and returns it. If the queue is empty, it returns-1and changes nothing.front()returns the value at the front without removing it, or-1if the queue is empty.size()returns the number of values in the queue.
Keep the values in one array of length capacity, made in the constructor. Do not use a library queue or
deque, or a list that grows. Each method must run in O(1) time.
Your class is tested by replaying a list of calls on a new ArrayQueue(capacity). ops[i] names the i-th
call: "enqueue", "dequeue", "front" or "size". The enqueues take their values from values in order,
so the first enqueue is given values[0], the second values[1], and so on, even when an enqueue drops its
value. The answer is the list of every value that dequeue, front and size return, in the order of the
calls.
In C# and Go the methods are Enqueue, Dequeue, Front and Size. Go creates the queue with
Constructor(capacity), and Rust with ArrayQueue::new(capacity). The names in ops are the same in every
language.
Example 1
Input: capacity = 3
ops = ["enqueue",
"enqueue",
"enqueue",
"enqueue",
"dequeue",
"enqueue",
"size",
"dequeue",
"dequeue",
"front"]
values = [4, 9, 2, 7, 5]
[4,3,9,2,5]Explanation: After three enqueues the queue is full, so enqueue(7) drops 7. dequeue removes 4, the oldest value,
which makes room for 5. The rest come out in the order they went in: 9, then 2, and 5 is left at the front.
Example 2
Input: capacity = 2
ops = ["dequeue",
"front",
"size",
"enqueue",
"front",
"dequeue",
"dequeue",
"size"]
values = [0]
[-1,-1,0,0,0,-1,0]Explanation: On an empty queue, dequeue and front return -1 and change nothing. The 0 that goes in later is a real
value, so front and dequeue return 0 for it.
Example 3
Input: capacity = 1
ops = ["enqueue",
"enqueue",
"front",
"dequeue",
"enqueue",
"dequeue",
"size"]
values = [1000000000, 8, 8]
[1000000000,1000000000,8,0]Explanation: With room for one value, the first 8 is dropped. The second 8 goes in only after 1000000000 has left.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ capacity ≤ 1051 ≤ ops.length ≤ 2 × 105- Each
ops[i]is"enqueue","dequeue","front"or"size". values.lengthequals the number of"enqueue"calls inops.0 ≤ values[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.